repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarAutomationStrings.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal static class NavigationBarAutomationStrings { public const string ProjectDropdownName = "Projects"; public const string ProjectDropdownId = "ProjectsList"; public const string TypeDropdownName = "Objects"; public const string TypeDropdownId = "ScopesList"; public const string MemberDropdownName = "Members"; public const string MemberDropdownId = "FunctionsList"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal static class NavigationBarAutomationStrings { public const string ProjectDropdownName = "Projects"; public const string ProjectDropdownId = "ProjectsList"; public const string TypeDropdownName = "Objects"; public const string TypeDropdownId = "ScopesList"; public const string MemberDropdownName = "Members"; public const string MemberDropdownId = "FunctionsList"; } }
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/VisualBasic/Tests/ConvertAnonymousTypeToTuple/ConvertAnonymousTypeToTupleTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertAnonymousTypeToTuple Partial Public Class ConvertAnonymousTypeToTupleTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicConvertAnonymousTypeToTupleDiagnosticAnalyzer(), New VisualBasicConvertAnonymousTypeToTupleCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertSingleAnonymousType() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function NotOnEmptyAnonymousType() As Task Await TestMissingInRegularAndScriptAsync(" class Test sub Method() dim t1 = [||]new with { } end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function NotOnSingleFieldAnonymousType() As Task Await TestMissingInRegularAndScriptAsync(" class Test sub Method() dim t1 = [||]new with { .a = 1 } end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertSingleAnonymousTypeWithInferredName() As Task Dim text = " class Test sub Method(b as integer) dim t1 = [||]new with { .a = 1, b } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleInstancesInSameMethod() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleInstancesAcrossMethods() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function OnlyConvertMatchingTypesInSameMethod() As Task Dim text = " class Test sub Method(b as integer) dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, b } dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b) dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllInSingleMethod() As Task Dim text = " class Test sub Method(b as integer) dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, b } dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b) dim t3 = new with { .a = 4 } dim t4 = (b:=5, a:=6) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllAcrossMethods() As Task Dim text = " class Test sub Method() dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub sub Method2() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllNestedTypes() As Task Dim text = " class Test sub Method() dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = new with { .c = 1, .d = 2 } } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=(c:=1, d:=2)) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleNestedInstancesInSameMethod() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = directcast(new with { .a = 1, .b = directcast(nothing, object) }, object) } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=directcast((a:=1, b:=directcast(nothing, object)), object)) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestInLambda1() As Task Dim text = " Imports System class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim a as Action = sub() dim t2 = new with { .a = 3, .b = 4 } end sub end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:=1, b:=2) dim a as Action = sub() dim t2 = (a:=3, b:=4) end sub end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestInLambda2() As Task Dim text = " Imports System class Test sub Method() dim t1 = new with { .a = 1, .b = 2 } dim a as Action = sub() dim t2 = [||]new with { .a = 3, .b = 4 } end sub end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:=1, b:=2) dim a as Action = sub() dim t2 = (a:=3, b:=4) end sub end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestIncomplete() As Task Dim text = " Imports System class Test sub Method() dim t1 = [||]new with { .a = , .b = } end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:= , b:= ) end sub end class " Await TestInRegularAndScriptAsync(text, expected) 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.ConvertAnonymousTypeToTuple Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertAnonymousTypeToTuple Partial Public Class ConvertAnonymousTypeToTupleTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicConvertAnonymousTypeToTupleDiagnosticAnalyzer(), New VisualBasicConvertAnonymousTypeToTupleCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertSingleAnonymousType() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function NotOnEmptyAnonymousType() As Task Await TestMissingInRegularAndScriptAsync(" class Test sub Method() dim t1 = [||]new with { } end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function NotOnSingleFieldAnonymousType() As Task Await TestMissingInRegularAndScriptAsync(" class Test sub Method() dim t1 = [||]new with { .a = 1 } end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertSingleAnonymousTypeWithInferredName() As Task Dim text = " class Test sub Method(b as integer) dim t1 = [||]new with { .a = 1, b } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleInstancesInSameMethod() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleInstancesAcrossMethods() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function OnlyConvertMatchingTypesInSameMethod() As Task Dim text = " class Test sub Method(b as integer) dim t1 = [||]new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, b } dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b) dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllInSingleMethod() As Task Dim text = " class Test sub Method(b as integer) dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, b } dim t3 = new with { .a = 4 } dim t4 = new with { .b = 5, .a = 6 } end sub end class " Dim expected = " class Test sub Method(b as integer) dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b) dim t3 = new with { .a = 4 } dim t4 = (b:=5, a:=6) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllAcrossMethods() As Task Dim text = " class Test sub Method() dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub sub Method2() dim t1 = new with { .a = 1, .b = 2 } dim t2 = new with { .a = 3, .b = 4 } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub sub Method2() dim t1 = (a:=1, b:=2) dim t2 = (a:=3, b:=4) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestFixAllNestedTypes() As Task Dim text = " class Test sub Method() dim t1 = {|FixAllInDocument:|}new with { .a = 1, .b = new with { .c = 1, .d = 2 } } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=(c:=1, d:=2)) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function ConvertMultipleNestedInstancesInSameMethod() As Task Dim text = " class Test sub Method() dim t1 = [||]new with { .a = 1, .b = directcast(new with { .a = 1, .b = directcast(nothing, object) }, object) } end sub end class " Dim expected = " class Test sub Method() dim t1 = (a:=1, b:=directcast((a:=1, b:=directcast(nothing, object)), object)) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestInLambda1() As Task Dim text = " Imports System class Test sub Method() dim t1 = [||]new with { .a = 1, .b = 2 } dim a as Action = sub() dim t2 = new with { .a = 3, .b = 4 } end sub end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:=1, b:=2) dim a as Action = sub() dim t2 = (a:=3, b:=4) end sub end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestInLambda2() As Task Dim text = " Imports System class Test sub Method() dim t1 = new with { .a = 1, .b = 2 } dim a as Action = sub() dim t2 = [||]new with { .a = 3, .b = 4 } end sub end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:=1, b:=2) dim a as Action = sub() dim t2 = (a:=3, b:=4) end sub end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToTuple)> Public Async Function TestIncomplete() As Task Dim text = " Imports System class Test sub Method() dim t1 = [||]new with { .a = , .b = } end sub end class " Dim expected = " Imports System class Test sub Method() dim t1 = (a:= , b:= ) end sub end class " Await TestInRegularAndScriptAsync(text, expected) End Function End Class End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/UnusedReferences/TestProjectAssetsFile.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports Microsoft.CodeAnalysis.UnusedReferences Imports Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.ProjectAssets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.UnusedReferences Friend Module TestProjectAssetsFile Public Function Create( version As Integer, targetFramework As String, references As ImmutableArray(Of ReferenceInfo)) As ProjectAssetsFile Dim allReferences = New List(Of ReferenceInfo) FlattenReferences(references, allReferences) Dim libraries = BuildLibraries(allReferences) Dim targets = BuildTargets(targetFramework, allReferences) Dim project = BuildProject(targetFramework) Dim projectAssets As ProjectAssetsFile = New ProjectAssetsFile With { .Version = version, .Targets = targets, .Libraries = libraries, .Project = project } Return projectAssets End Function Private Sub FlattenReferences(references As ImmutableArray(Of ReferenceInfo), allReferences As List(Of ReferenceInfo)) For Each reference In references FlattenReference(reference, allReferences) Next End Sub Private Sub FlattenReference(reference As ReferenceInfo, allReferences As List(Of ReferenceInfo)) allReferences.Add(reference) FlattenReferences(reference.Dependencies, allReferences) End Sub Private Function BuildLibraries(references As List(Of ReferenceInfo)) As Dictionary(Of String, ProjectAssetsLibrary) Dim libraries = New Dictionary(Of String, ProjectAssetsLibrary) For Each reference In references Dim library = New ProjectAssetsLibrary With { .Path = reference.ItemSpecification } libraries.Add(Path.GetFileNameWithoutExtension(library.Path), library) Next Return libraries End Function Private Function BuildTargets(targetFramework As String, references As List(Of ReferenceInfo)) As Dictionary(Of String, Dictionary(Of String, ProjectAssetsTargetLibrary)) Dim libraries = New Dictionary(Of String, ProjectAssetsTargetLibrary) For Each reference In references Dim dependencies = BuildDependencies(reference.Dependencies) Dim library = New ProjectAssetsTargetLibrary With { .Type = GetLibraryType(reference.ReferenceType), .Compile = New Dictionary(Of String, ProjectAssetsTargetLibraryCompile) From { {Path.ChangeExtension(reference.ItemSpecification, "dll"), Nothing} }, .Dependencies = dependencies } libraries(Path.GetFileNameWithoutExtension(reference.ItemSpecification)) = library Next Return New Dictionary(Of String, Dictionary(Of String, ProjectAssetsTargetLibrary)) From { {targetFramework, libraries} } End Function Private Function GetLibraryType(referenceType As ReferenceType) As String If referenceType = ReferenceType.Package Then Return "package" If referenceType = ReferenceType.Project Then Return "project" Return "assembly" End Function Private Function BuildDependencies(references As ImmutableArray(Of ReferenceInfo)) As Dictionary(Of String, String) Return references.ToDictionary( Function(reference) Return Path.GetFileNameWithoutExtension(reference.ItemSpecification) End Function, Function(reference) Return String.Empty End Function) End Function Private Function BuildProject(targetFramework As String) As ProjectAssetsProject ' Frameworks won't always specify a set of dependencies. ' This ensures the project asset reader does not error in these cases. Return New ProjectAssetsProject With { .Frameworks = New Dictionary(Of String, ProjectAssetsProjectFramework) From { {targetFramework, New ProjectAssetsProjectFramework} } } End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports Microsoft.CodeAnalysis.UnusedReferences Imports Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.ProjectAssets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.UnusedReferences Friend Module TestProjectAssetsFile Public Function Create( version As Integer, targetFramework As String, references As ImmutableArray(Of ReferenceInfo)) As ProjectAssetsFile Dim allReferences = New List(Of ReferenceInfo) FlattenReferences(references, allReferences) Dim libraries = BuildLibraries(allReferences) Dim targets = BuildTargets(targetFramework, allReferences) Dim project = BuildProject(targetFramework) Dim projectAssets As ProjectAssetsFile = New ProjectAssetsFile With { .Version = version, .Targets = targets, .Libraries = libraries, .Project = project } Return projectAssets End Function Private Sub FlattenReferences(references As ImmutableArray(Of ReferenceInfo), allReferences As List(Of ReferenceInfo)) For Each reference In references FlattenReference(reference, allReferences) Next End Sub Private Sub FlattenReference(reference As ReferenceInfo, allReferences As List(Of ReferenceInfo)) allReferences.Add(reference) FlattenReferences(reference.Dependencies, allReferences) End Sub Private Function BuildLibraries(references As List(Of ReferenceInfo)) As Dictionary(Of String, ProjectAssetsLibrary) Dim libraries = New Dictionary(Of String, ProjectAssetsLibrary) For Each reference In references Dim library = New ProjectAssetsLibrary With { .Path = reference.ItemSpecification } libraries.Add(Path.GetFileNameWithoutExtension(library.Path), library) Next Return libraries End Function Private Function BuildTargets(targetFramework As String, references As List(Of ReferenceInfo)) As Dictionary(Of String, Dictionary(Of String, ProjectAssetsTargetLibrary)) Dim libraries = New Dictionary(Of String, ProjectAssetsTargetLibrary) For Each reference In references Dim dependencies = BuildDependencies(reference.Dependencies) Dim library = New ProjectAssetsTargetLibrary With { .Type = GetLibraryType(reference.ReferenceType), .Compile = New Dictionary(Of String, ProjectAssetsTargetLibraryCompile) From { {Path.ChangeExtension(reference.ItemSpecification, "dll"), Nothing} }, .Dependencies = dependencies } libraries(Path.GetFileNameWithoutExtension(reference.ItemSpecification)) = library Next Return New Dictionary(Of String, Dictionary(Of String, ProjectAssetsTargetLibrary)) From { {targetFramework, libraries} } End Function Private Function GetLibraryType(referenceType As ReferenceType) As String If referenceType = ReferenceType.Package Then Return "package" If referenceType = ReferenceType.Project Then Return "project" Return "assembly" End Function Private Function BuildDependencies(references As ImmutableArray(Of ReferenceInfo)) As Dictionary(Of String, String) Return references.ToDictionary( Function(reference) Return Path.GetFileNameWithoutExtension(reference.ItemSpecification) End Function, Function(reference) Return String.Empty End Function) End Function Private Function BuildProject(targetFramework As String) As ProjectAssetsProject ' Frameworks won't always specify a set of dependencies. ' This ensures the project asset reader does not error in these cases. Return New ProjectAssetsProject With { .Frameworks = New Dictionary(Of String, ProjectAssetsProjectFramework) From { {targetFramework, New ProjectAssetsProjectFramework} } } End Function End Module End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Analysis/MissingRuntimeMemberDiagnosticHelper.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis Friend Module MissingRuntimeMemberDiagnosticHelper Friend Const MyVBNamespace As String = "My" ' Details on these types and the feature name which is displayed in the diagnostic ' for those items missing in VB Core compilation. Private ReadOnly s_metadataNames As New Dictionary(Of String, String) From { {"Microsoft.VisualBasic.CompilerServices.Operators", "Late binding"}, {"Microsoft.VisualBasic.CompilerServices.NewLateBinding", "Late binding"}, {"Microsoft.VisualBasic.CompilerServices.LikeOperator", "Like operator"}, {"Microsoft.VisualBasic.CompilerServices.ProjectData", "Unstructured exception handling"}, {"Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError", "Unstructured exception handling"} } Friend Function GetDiagnosticForMissingRuntimeHelper(typename As String, membername As String, embedVBCoreRuntime As Boolean) As DiagnosticInfo Dim diag As DiagnosticInfo ' Depending upon whether the vbruntime embed compilation option is used and this is a function we have intentionally ' omitted from VB will determine which diagnostic is reported. ' Examples ' (Late binding, old style error handling, like operator, Err Object) - with VB Embed - report new diagnostic ' (Late binding, old style error handling, like operator) - without VB Embed just no reference to microsoft.visualbasic.dll - report old diagnostic Dim verifiedTypename As String = "" s_metadataNames.TryGetValue(typename, verifiedTypename) If embedVBCoreRuntime AndAlso (Not String.IsNullOrEmpty(verifiedTypename)) Then 'Check to see the compilation options included VB. diag = ErrorFactory.ErrorInfo(ERRID.ERR_PlatformDoesntSupport, verifiedTypename) Else diag = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, typename & "." & membername) End If Return diag End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis Friend Module MissingRuntimeMemberDiagnosticHelper Friend Const MyVBNamespace As String = "My" ' Details on these types and the feature name which is displayed in the diagnostic ' for those items missing in VB Core compilation. Private ReadOnly s_metadataNames As New Dictionary(Of String, String) From { {"Microsoft.VisualBasic.CompilerServices.Operators", "Late binding"}, {"Microsoft.VisualBasic.CompilerServices.NewLateBinding", "Late binding"}, {"Microsoft.VisualBasic.CompilerServices.LikeOperator", "Like operator"}, {"Microsoft.VisualBasic.CompilerServices.ProjectData", "Unstructured exception handling"}, {"Microsoft.VisualBasic.CompilerServices.ProjectData.CreateProjectError", "Unstructured exception handling"} } Friend Function GetDiagnosticForMissingRuntimeHelper(typename As String, membername As String, embedVBCoreRuntime As Boolean) As DiagnosticInfo Dim diag As DiagnosticInfo ' Depending upon whether the vbruntime embed compilation option is used and this is a function we have intentionally ' omitted from VB will determine which diagnostic is reported. ' Examples ' (Late binding, old style error handling, like operator, Err Object) - with VB Embed - report new diagnostic ' (Late binding, old style error handling, like operator) - without VB Embed just no reference to microsoft.visualbasic.dll - report old diagnostic Dim verifiedTypename As String = "" s_metadataNames.TryGetValue(typename, verifiedTypename) If embedVBCoreRuntime AndAlso (Not String.IsNullOrEmpty(verifiedTypename)) Then 'Check to see the compilation options included VB. diag = ErrorFactory.ErrorInfo(ERRID.ERR_PlatformDoesntSupport, verifiedTypename) Else diag = ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, typename & "." & membername) End If Return diag End Function End Module End Namespace
-1
dotnet/roslyn
54,984
Fix 'organize usings' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:35:34Z
2021-07-20T22:10:43Z
b5b5a31e1edd0205c745bf0c64ff850985544e5f
59819f82775f0fcf5a1ab66754d8cfebb7f2250b
Fix 'organize usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests_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.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyTypeNames { public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInDocument:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInProject:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInSolution:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_SimplifyMemberAccess() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; {|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyTypeNames { public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { #region "Fix all occurrences tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInDocument:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInProject:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static System.Int32 F(System.Int32 x, System.Int16 y) { {|FixAllInSolution:System.Int32|} i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, short y) { int i1 = 0; short s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: PreferIntrinsicTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_SimplifyMemberAccess() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; {|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; Console.Write(i1 + s1 + i2); Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Classification/ClassificationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; return 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; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; return result; } } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is NamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.CompilationUnit => ((CompilationUnitSyntax)declaration).Usings, SyntaxKind.NamespaceDeclaration => ((NamespaceDeclarationSyntax)declaration).Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); switch (declaration.Kind()) { case SyntaxKind.CompilationUnit: var cu = (CompilationUnitSyntax)declaration; return cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)); case SyntaxKind.NamespaceDeclaration: var nd = (NamespaceDeclarationSyntax)declaration; return nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, NamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), NamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) { switch (declaration) { case InterfaceDeclarationSyntax: return this.AsInterfaceMember(member); case TypeDeclarationSyntax typeDeclaration: return this.AsClassMember(member, typeDeclaration.Identifier.Text); case EnumDeclarationSyntax: return this.AsEnumMember(member); case NamespaceDeclarationSyntax: return AsNamespaceMember(member); case CompilationUnitSyntax: return AsNamespaceMember(member); default: return null; } } public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, NamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), NamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.Usings, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); return declaration switch { CompilationUnitSyntax cu => cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)), BaseNamespaceDeclarationSyntax nd => nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)), _ => declaration, }; } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, BaseNamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), BaseNamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) => declaration switch { InterfaceDeclarationSyntax => this.AsInterfaceMember(member), TypeDeclarationSyntax typeDeclaration => this.AsClassMember(member, typeDeclaration.Identifier.Text), EnumDeclarationSyntax => this.AsEnumMember(member), BaseNamespaceDeclarationSyntax => AsNamespaceMember(member), CompilationUnitSyntax => AsNamespaceMember(member), _ => null, }; public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), BaseNamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; #nullable enable internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode> #nullable disable { protected readonly bool VisitIntoStructuredTrivia; public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) { this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia; } public override CSharpSyntaxNode VisitToken(SyntaxToken token) { var leading = this.VisitList(token.LeadingTrivia); var trailing = this.VisitList(token.TrailingTrivia); if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia) { if (leading != token.LeadingTrivia) { token = token.TokenWithLeadingTrivia(leading.Node); } if (trailing != token.TrailingTrivia) { token = token.TokenWithTrailingTrivia(trailing.Node); } } return token; } public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode { SyntaxListBuilder alternate = null; for (int i = 0, n = list.Count; i < n; i++) { var item = list[i]; var visited = this.Visit(item); if (item != visited && alternate == null) { alternate = new SyntaxListBuilder(n); alternate.AddRange(list, 0, i); } if (alternate != null) { Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter."); alternate.Add(visited); } } if (alternate != null) { return alternate.ToList(); } return list; } public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode { // A separated list is filled with C# nodes and C# tokens. Both of which // derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately // typesafe. var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators(); var result = this.VisitList(withSeps); if (result != withSeps) { return result.AsSeparatedList<TNode>(); } return list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; #nullable enable internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode> #nullable disable { protected readonly bool VisitIntoStructuredTrivia; public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false) { this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia; } public override CSharpSyntaxNode VisitToken(SyntaxToken token) { var leading = this.VisitList(token.LeadingTrivia); var trailing = this.VisitList(token.TrailingTrivia); if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia) { if (leading != token.LeadingTrivia) { token = token.TokenWithLeadingTrivia(leading.Node); } if (trailing != token.TrailingTrivia) { token = token.TokenWithTrailingTrivia(trailing.Node); } } return token; } public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode { SyntaxListBuilder alternate = null; for (int i = 0, n = list.Count; i < n; i++) { var item = list[i]; var visited = this.Visit(item); if (item != visited && alternate == null) { alternate = new SyntaxListBuilder(n); alternate.AddRange(list, 0, i); } if (alternate != null) { Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter."); alternate.Add(visited); } } if (alternate != null) { return alternate.ToList(); } return list; } public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode { // A separated list is filled with C# nodes and C# tokens. Both of which // derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately // typesafe. var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators(); var result = this.VisitList(withSeps); if (result != withSeps) { return result.AsSeparatedList<TNode>(); } return list; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/EditAndContinue/ProjectAnalysisSummary.cs
// Licensed to the .NET Foundation under one or more 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.EditAndContinue { internal enum ProjectAnalysisSummary { /// <summary> /// Project hasn't been changed. /// </summary> NoChanges, /// <summary> /// Project contains compilation errors that block EnC analysis. /// </summary> CompilationErrors, /// <summary> /// Project contains rude edits. /// </summary> RudeEdits, /// <summary> /// The project only changed in comments, whitespaces, etc. that don't require compilation. /// </summary> ValidInsignificantChanges, /// <summary> /// The project contains valid changes that require application of a delta. /// </summary> ValidChanges } }
// Licensed to the .NET Foundation under one or more 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.EditAndContinue { internal enum ProjectAnalysisSummary { /// <summary> /// Project hasn't been changed. /// </summary> NoChanges, /// <summary> /// Project contains compilation errors that block EnC analysis. /// </summary> CompilationErrors, /// <summary> /// Project contains rude edits. /// </summary> RudeEdits, /// <summary> /// The project only changed in comments, whitespaces, etc. that don't require compilation. /// </summary> ValidInsignificantChanges, /// <summary> /// The project contains valid changes that require application of a delta. /// </summary> ValidChanges } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Serialization/SerializerService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService : ISerializerService { [ExportWorkspaceServiceFactory(typeof(ISerializerService), layer: ServiceLayer.Default), Shared] internal sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SerializerService(workspaceServices); } private static readonly Func<WellKnownSynchronizationKind, string> s_logKind = k => k.ToString(); private readonly HostWorkspaceServices _workspaceServices; private readonly ITemporaryStorageService _storageService; private readonly ITextFactoryService _textService; private readonly IDocumentationProviderService? _documentationService; private readonly IAnalyzerAssemblyLoaderProvider _analyzerLoaderProvider; private readonly ConcurrentDictionary<string, IOptionsSerializationService> _lazyLanguageSerializationService; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private protected SerializerService(HostWorkspaceServices workspaceServices) { _workspaceServices = workspaceServices; _storageService = workspaceServices.GetRequiredService<ITemporaryStorageService>(); _textService = workspaceServices.GetRequiredService<ITextFactoryService>(); _analyzerLoaderProvider = workspaceServices.GetRequiredService<IAnalyzerAssemblyLoaderProvider>(); _documentationService = workspaceServices.GetService<IDocumentationProviderService>(); _lazyLanguageSerializationService = new ConcurrentDictionary<string, IOptionsSerializationService>(concurrencyLevel: 2, capacity: _workspaceServices.SupportedLanguages.Count()); } public Checksum CreateChecksum(object value, CancellationToken cancellationToken) { var kind = value.GetWellKnownSynchronizationKind(); using (Logger.LogBlock(FunctionId.Serializer_CreateChecksum, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (value is IChecksummedObject checksummedObject) { return checksummedObject.Checksum; } switch (kind) { case WellKnownSynchronizationKind.Null: return Checksum.Null; case WellKnownSynchronizationKind.CompilationOptions: case WellKnownSynchronizationKind.ParseOptions: case WellKnownSynchronizationKind.ProjectReference: case WellKnownSynchronizationKind.OptionSet: case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: return Checksum.Create(value, this); case WellKnownSynchronizationKind.MetadataReference: return Checksum.Create(CreateChecksum((MetadataReference)value, cancellationToken)); case WellKnownSynchronizationKind.AnalyzerReference: return Checksum.Create(CreateChecksum((AnalyzerReference)value, cancellationToken)); case WellKnownSynchronizationKind.SerializableSourceText: return Checksum.Create(((SerializableSourceText)value).GetChecksum()); case WellKnownSynchronizationKind.SourceText: return Checksum.Create(((SourceText)value).GetChecksum()); default: // object that is not part of solution is not supported since we don't know what inputs are required to // serialize it throw ExceptionUtilities.UnexpectedValue(kind); } } } public void Serialize(object value, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var kind = value.GetWellKnownSynchronizationKind(); using (Logger.LogBlock(FunctionId.Serializer_Serialize, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (value is ChecksumWithChildren checksumWithChildren) { SerializeChecksumWithChildren(checksumWithChildren, writer, cancellationToken); return; } switch (kind) { case WellKnownSynchronizationKind.Null: // do nothing return; case WellKnownSynchronizationKind.SolutionAttributes: case WellKnownSynchronizationKind.ProjectAttributes: case WellKnownSynchronizationKind.DocumentAttributes: case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: ((IObjectWritable)value).WriteTo(writer); return; case WellKnownSynchronizationKind.CompilationOptions: SerializeCompilationOptions((CompilationOptions)value, writer, cancellationToken); return; case WellKnownSynchronizationKind.ParseOptions: cancellationToken.ThrowIfCancellationRequested(); SerializeParseOptions((ParseOptions)value, writer); return; case WellKnownSynchronizationKind.ProjectReference: SerializeProjectReference((ProjectReference)value, writer, cancellationToken); return; case WellKnownSynchronizationKind.MetadataReference: SerializeMetadataReference((MetadataReference)value, writer, context, cancellationToken); return; case WellKnownSynchronizationKind.AnalyzerReference: SerializeAnalyzerReference((AnalyzerReference)value, writer, cancellationToken: cancellationToken); return; case WellKnownSynchronizationKind.SerializableSourceText: SerializeSourceText((SerializableSourceText)value, writer, context, cancellationToken); return; case WellKnownSynchronizationKind.SourceText: SerializeSourceText(new SerializableSourceText((SourceText)value), writer, context, cancellationToken); return; case WellKnownSynchronizationKind.OptionSet: SerializeOptionSet((SerializableOptionSet)value, writer, cancellationToken); return; default: // object that is not part of solution is not supported since we don't know what inputs are required to // serialize it throw ExceptionUtilities.UnexpectedValue(kind); } } } public T? Deserialize<T>(WellKnownSynchronizationKind kind, ObjectReader reader, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Serializer_Deserialize, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); switch (kind) { case WellKnownSynchronizationKind.Null: return default; case WellKnownSynchronizationKind.SolutionState: case WellKnownSynchronizationKind.ProjectState: case WellKnownSynchronizationKind.DocumentState: case WellKnownSynchronizationKind.ChecksumCollection: return (T)(object)DeserializeChecksumWithChildren(reader, cancellationToken); case WellKnownSynchronizationKind.SolutionAttributes: return (T)(object)SolutionInfo.SolutionAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.ProjectAttributes: return (T)(object)ProjectInfo.ProjectAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.DocumentAttributes: return (T)(object)DocumentInfo.DocumentAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: return (T)(object)SourceGeneratedDocumentIdentity.ReadFrom(reader); case WellKnownSynchronizationKind.CompilationOptions: return (T)(object)DeserializeCompilationOptions(reader, cancellationToken); case WellKnownSynchronizationKind.ParseOptions: return (T)(object)DeserializeParseOptions(reader, cancellationToken); case WellKnownSynchronizationKind.ProjectReference: return (T)(object)DeserializeProjectReference(reader, cancellationToken); case WellKnownSynchronizationKind.MetadataReference: return (T)(object)DeserializeMetadataReference(reader, cancellationToken); case WellKnownSynchronizationKind.AnalyzerReference: return (T)(object)DeserializeAnalyzerReference(reader, cancellationToken); case WellKnownSynchronizationKind.SerializableSourceText: return (T)(object)DeserializeSerializableSourceText(reader, cancellationToken); case WellKnownSynchronizationKind.SourceText: return (T)(object)DeserializeSourceText(reader, cancellationToken); case WellKnownSynchronizationKind.OptionSet: return (T)(object)DeserializeOptionSet(reader, cancellationToken); default: throw ExceptionUtilities.UnexpectedValue(kind); } } } private IOptionsSerializationService GetOptionsSerializationService(string languageName) => _lazyLanguageSerializationService.GetOrAdd(languageName, n => _workspaceServices.GetLanguageServices(n).GetRequiredService<IOptionsSerializationService>()); public Checksum CreateParseOptionsChecksum(ParseOptions value) => Checksum.Create(value, this); } // TODO: convert this to sub class rather than using enum with if statement. internal enum SerializationKinds { Bits, FilePath, MemoryMapFile } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Serialization { internal partial class SerializerService : ISerializerService { [ExportWorkspaceServiceFactory(typeof(ISerializerService), layer: ServiceLayer.Default), Shared] internal sealed class Factory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SerializerService(workspaceServices); } private static readonly Func<WellKnownSynchronizationKind, string> s_logKind = k => k.ToString(); private readonly HostWorkspaceServices _workspaceServices; private readonly ITemporaryStorageService _storageService; private readonly ITextFactoryService _textService; private readonly IDocumentationProviderService? _documentationService; private readonly IAnalyzerAssemblyLoaderProvider _analyzerLoaderProvider; private readonly ConcurrentDictionary<string, IOptionsSerializationService> _lazyLanguageSerializationService; [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] private protected SerializerService(HostWorkspaceServices workspaceServices) { _workspaceServices = workspaceServices; _storageService = workspaceServices.GetRequiredService<ITemporaryStorageService>(); _textService = workspaceServices.GetRequiredService<ITextFactoryService>(); _analyzerLoaderProvider = workspaceServices.GetRequiredService<IAnalyzerAssemblyLoaderProvider>(); _documentationService = workspaceServices.GetService<IDocumentationProviderService>(); _lazyLanguageSerializationService = new ConcurrentDictionary<string, IOptionsSerializationService>(concurrencyLevel: 2, capacity: _workspaceServices.SupportedLanguages.Count()); } public Checksum CreateChecksum(object value, CancellationToken cancellationToken) { var kind = value.GetWellKnownSynchronizationKind(); using (Logger.LogBlock(FunctionId.Serializer_CreateChecksum, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (value is IChecksummedObject checksummedObject) { return checksummedObject.Checksum; } switch (kind) { case WellKnownSynchronizationKind.Null: return Checksum.Null; case WellKnownSynchronizationKind.CompilationOptions: case WellKnownSynchronizationKind.ParseOptions: case WellKnownSynchronizationKind.ProjectReference: case WellKnownSynchronizationKind.OptionSet: case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: return Checksum.Create(value, this); case WellKnownSynchronizationKind.MetadataReference: return Checksum.Create(CreateChecksum((MetadataReference)value, cancellationToken)); case WellKnownSynchronizationKind.AnalyzerReference: return Checksum.Create(CreateChecksum((AnalyzerReference)value, cancellationToken)); case WellKnownSynchronizationKind.SerializableSourceText: return Checksum.Create(((SerializableSourceText)value).GetChecksum()); case WellKnownSynchronizationKind.SourceText: return Checksum.Create(((SourceText)value).GetChecksum()); default: // object that is not part of solution is not supported since we don't know what inputs are required to // serialize it throw ExceptionUtilities.UnexpectedValue(kind); } } } public void Serialize(object value, ObjectWriter writer, SolutionReplicationContext context, CancellationToken cancellationToken) { var kind = value.GetWellKnownSynchronizationKind(); using (Logger.LogBlock(FunctionId.Serializer_Serialize, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (value is ChecksumWithChildren checksumWithChildren) { SerializeChecksumWithChildren(checksumWithChildren, writer, cancellationToken); return; } switch (kind) { case WellKnownSynchronizationKind.Null: // do nothing return; case WellKnownSynchronizationKind.SolutionAttributes: case WellKnownSynchronizationKind.ProjectAttributes: case WellKnownSynchronizationKind.DocumentAttributes: case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: ((IObjectWritable)value).WriteTo(writer); return; case WellKnownSynchronizationKind.CompilationOptions: SerializeCompilationOptions((CompilationOptions)value, writer, cancellationToken); return; case WellKnownSynchronizationKind.ParseOptions: cancellationToken.ThrowIfCancellationRequested(); SerializeParseOptions((ParseOptions)value, writer); return; case WellKnownSynchronizationKind.ProjectReference: SerializeProjectReference((ProjectReference)value, writer, cancellationToken); return; case WellKnownSynchronizationKind.MetadataReference: SerializeMetadataReference((MetadataReference)value, writer, context, cancellationToken); return; case WellKnownSynchronizationKind.AnalyzerReference: SerializeAnalyzerReference((AnalyzerReference)value, writer, cancellationToken: cancellationToken); return; case WellKnownSynchronizationKind.SerializableSourceText: SerializeSourceText((SerializableSourceText)value, writer, context, cancellationToken); return; case WellKnownSynchronizationKind.SourceText: SerializeSourceText(new SerializableSourceText((SourceText)value), writer, context, cancellationToken); return; case WellKnownSynchronizationKind.OptionSet: SerializeOptionSet((SerializableOptionSet)value, writer, cancellationToken); return; default: // object that is not part of solution is not supported since we don't know what inputs are required to // serialize it throw ExceptionUtilities.UnexpectedValue(kind); } } } public T? Deserialize<T>(WellKnownSynchronizationKind kind, ObjectReader reader, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Serializer_Deserialize, s_logKind, kind, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); switch (kind) { case WellKnownSynchronizationKind.Null: return default; case WellKnownSynchronizationKind.SolutionState: case WellKnownSynchronizationKind.ProjectState: case WellKnownSynchronizationKind.DocumentState: case WellKnownSynchronizationKind.ChecksumCollection: return (T)(object)DeserializeChecksumWithChildren(reader, cancellationToken); case WellKnownSynchronizationKind.SolutionAttributes: return (T)(object)SolutionInfo.SolutionAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.ProjectAttributes: return (T)(object)ProjectInfo.ProjectAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.DocumentAttributes: return (T)(object)DocumentInfo.DocumentAttributes.ReadFrom(reader); case WellKnownSynchronizationKind.SourceGeneratedDocumentIdentity: return (T)(object)SourceGeneratedDocumentIdentity.ReadFrom(reader); case WellKnownSynchronizationKind.CompilationOptions: return (T)(object)DeserializeCompilationOptions(reader, cancellationToken); case WellKnownSynchronizationKind.ParseOptions: return (T)(object)DeserializeParseOptions(reader, cancellationToken); case WellKnownSynchronizationKind.ProjectReference: return (T)(object)DeserializeProjectReference(reader, cancellationToken); case WellKnownSynchronizationKind.MetadataReference: return (T)(object)DeserializeMetadataReference(reader, cancellationToken); case WellKnownSynchronizationKind.AnalyzerReference: return (T)(object)DeserializeAnalyzerReference(reader, cancellationToken); case WellKnownSynchronizationKind.SerializableSourceText: return (T)(object)DeserializeSerializableSourceText(reader, cancellationToken); case WellKnownSynchronizationKind.SourceText: return (T)(object)DeserializeSourceText(reader, cancellationToken); case WellKnownSynchronizationKind.OptionSet: return (T)(object)DeserializeOptionSet(reader, cancellationToken); default: throw ExceptionUtilities.UnexpectedValue(kind); } } } private IOptionsSerializationService GetOptionsSerializationService(string languageName) => _lazyLanguageSerializationService.GetOrAdd(languageName, n => _workspaceServices.GetLanguageServices(n).GetRequiredService<IOptionsSerializationService>()); public Checksum CreateParseOptionsChecksum(ParseOptions value) => Checksum.Create(value, this); } // TODO: convert this to sub class rather than using enum with if statement. internal enum SerializationKinds { Bits, FilePath, MemoryMapFile } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/WinRt/WinMDPrefixing.cs
// This is the source for WinMDPrefixing.winmd. To generate a copy of // WinMDPrefixing.winmd executive the following commands: // csc.exe /t:winmdobj WinMDPrefixing.cs // winmdexp [/r: references to mscorlib, System.Runtime.dll, and windows.winmd] WinMDPrefixing.winmdobj namespace WinMDPrefixing { public sealed class TestClass : TestInterface { } public interface TestInterface { } public delegate void TestDelegate(); public struct TestStruct { public int TestField; } }
// This is the source for WinMDPrefixing.winmd. To generate a copy of // WinMDPrefixing.winmd executive the following commands: // csc.exe /t:winmdobj WinMDPrefixing.cs // winmdexp [/r: references to mscorlib, System.Runtime.dll, and windows.winmd] WinMDPrefixing.winmdobj namespace WinMDPrefixing { public sealed class TestClass : TestInterface { } public interface TestInterface { } public delegate void TestDelegate(); public struct TestStruct { public int TestField; } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/Core/Hosting/ObjectFormatter/CommonTypeNameFormatterOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Scripting.Hosting { internal struct CommonTypeNameFormatterOptions { public int ArrayBoundRadix { get; } public bool ShowNamespaces { get; } public CommonTypeNameFormatterOptions(int arrayBoundRadix, bool showNamespaces) { ArrayBoundRadix = arrayBoundRadix; ShowNamespaces = showNamespaces; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Scripting.Hosting { internal struct CommonTypeNameFormatterOptions { public int ArrayBoundRadix { get; } public bool ShowNamespaces { get; } public CommonTypeNameFormatterOptions(int arrayBoundRadix, bool showNamespaces) { ArrayBoundRadix = arrayBoundRadix; ShowNamespaces = showNamespaces; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingNamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a namespace of a RetargetingModuleSymbol. Essentially this is a wrapper around /// another NamespaceSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal sealed class RetargetingNamespaceSymbol : NamespaceSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; /// <summary> /// The underlying NamespaceSymbol, cannot be another RetargetingNamespaceSymbol. /// </summary> private readonly NamespaceSymbol _underlyingNamespace; public RetargetingNamespaceSymbol(RetargetingModuleSymbol retargetingModule, NamespaceSymbol underlyingNamespace) { Debug.Assert((object)retargetingModule != null); Debug.Assert((object)underlyingNamespace != null); Debug.Assert(!(underlyingNamespace is RetargetingNamespaceSymbol)); _retargetingModule = retargetingModule; _underlyingNamespace = underlyingNamespace; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public NamespaceSymbol UnderlyingNamespace { get { return _underlyingNamespace; } } internal override NamespaceExtent Extent { get { return new NamespaceExtent(_retargetingModule); } } public override ImmutableArray<Symbol> GetMembers() { return RetargetMembers(_underlyingNamespace.GetMembers()); } private ImmutableArray<Symbol> RetargetMembers(ImmutableArray<Symbol> underlyingMembers) { var builder = ArrayBuilder<Symbol>.GetInstance(underlyingMembers.Length); foreach (Symbol s in underlyingMembers) { // Skip explicitly declared local types. if (s.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { continue; } builder.Add(this.RetargetingTranslator.Retarget(s)); } return builder.ToImmutableAndFree(); } internal override ImmutableArray<Symbol> GetMembersUnordered() { return RetargetMembers(_underlyingNamespace.GetMembersUnordered()); } public override ImmutableArray<Symbol> GetMembers(string name) { return RetargetMembers(_underlyingNamespace.GetMembers(name)); } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembersUnordered()); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers()); } private ImmutableArray<NamedTypeSymbol> RetargetTypeMembers(ImmutableArray<NamedTypeSymbol> underlyingMembers) { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(underlyingMembers.Length); foreach (NamedTypeSymbol t in underlyingMembers) { // Skip explicitly declared local types. if (t.IsExplicitDefinitionOfNoPiaLocalType) { continue; } Debug.Assert(t.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); builder.Add(this.RetargetingTranslator.Retarget(t, RetargetOptions.RetargetPrimitiveTypesByName)); } return builder.ToImmutableAndFree(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name)); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name, arity)); } public override Symbol ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingNamespace.ContainingSymbol); } } public override ImmutableArray<Location> Locations { get { return _retargetingModule.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingNamespace.DeclaringSyntaxReferences; } } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } public override bool IsGlobalNamespace { get { return _underlyingNamespace.IsGlobalNamespace; } } public override string Name { get { return _underlyingNamespace.Name; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingNamespace.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName) { // This method is invoked when looking up a type by metadata type // name through a RetargetingAssemblySymbol. For instance, in // UnitTests.Symbols.Metadata.PE.NoPia.LocalTypeSubstitution2. NamedTypeSymbol underlying = _underlyingNamespace.LookupMetadataType(ref typeName); Debug.Assert((object)underlying.ContainingModule == (object)_retargetingModule.UnderlyingModule); if (!underlying.IsErrorType() && underlying.IsExplicitDefinitionOfNoPiaLocalType) { // Explicitly defined local types should be hidden. return new MissingMetadataTypeSymbol.TopLevel(_retargetingModule, ref typeName); } return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } internal override void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var underlyingMethods = ArrayBuilder<MethodSymbol>.GetInstance(); _underlyingNamespace.GetExtensionMethods(underlyingMethods, nameOpt, arity, options); foreach (var underlyingMethod in underlyingMethods) { methods.Add(this.RetargetingTranslator.Retarget(underlyingMethod)); } underlyingMethods.Free(); } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; using System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { /// <summary> /// Represents a namespace of a RetargetingModuleSymbol. Essentially this is a wrapper around /// another NamespaceSymbol that is responsible for retargeting symbols from one assembly to another. /// It can retarget symbols for multiple assemblies at the same time. /// </summary> internal sealed class RetargetingNamespaceSymbol : NamespaceSymbol { /// <summary> /// Owning RetargetingModuleSymbol. /// </summary> private readonly RetargetingModuleSymbol _retargetingModule; /// <summary> /// The underlying NamespaceSymbol, cannot be another RetargetingNamespaceSymbol. /// </summary> private readonly NamespaceSymbol _underlyingNamespace; public RetargetingNamespaceSymbol(RetargetingModuleSymbol retargetingModule, NamespaceSymbol underlyingNamespace) { Debug.Assert((object)retargetingModule != null); Debug.Assert((object)underlyingNamespace != null); Debug.Assert(!(underlyingNamespace is RetargetingNamespaceSymbol)); _retargetingModule = retargetingModule; _underlyingNamespace = underlyingNamespace; } private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator { get { return _retargetingModule.RetargetingTranslator; } } public NamespaceSymbol UnderlyingNamespace { get { return _underlyingNamespace; } } internal override NamespaceExtent Extent { get { return new NamespaceExtent(_retargetingModule); } } public override ImmutableArray<Symbol> GetMembers() { return RetargetMembers(_underlyingNamespace.GetMembers()); } private ImmutableArray<Symbol> RetargetMembers(ImmutableArray<Symbol> underlyingMembers) { var builder = ArrayBuilder<Symbol>.GetInstance(underlyingMembers.Length); foreach (Symbol s in underlyingMembers) { // Skip explicitly declared local types. if (s.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { continue; } builder.Add(this.RetargetingTranslator.Retarget(s)); } return builder.ToImmutableAndFree(); } internal override ImmutableArray<Symbol> GetMembersUnordered() { return RetargetMembers(_underlyingNamespace.GetMembersUnordered()); } public override ImmutableArray<Symbol> GetMembers(string name) { return RetargetMembers(_underlyingNamespace.GetMembers(name)); } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembersUnordered()); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers()); } private ImmutableArray<NamedTypeSymbol> RetargetTypeMembers(ImmutableArray<NamedTypeSymbol> underlyingMembers) { var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(underlyingMembers.Length); foreach (NamedTypeSymbol t in underlyingMembers) { // Skip explicitly declared local types. if (t.IsExplicitDefinitionOfNoPiaLocalType) { continue; } Debug.Assert(t.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); builder.Add(this.RetargetingTranslator.Retarget(t, RetargetOptions.RetargetPrimitiveTypesByName)); } return builder.ToImmutableAndFree(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name)); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return RetargetTypeMembers(_underlyingNamespace.GetTypeMembers(name, arity)); } public override Symbol ContainingSymbol { get { return this.RetargetingTranslator.Retarget(_underlyingNamespace.ContainingSymbol); } } public override ImmutableArray<Location> Locations { get { return _retargetingModule.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingNamespace.DeclaringSyntaxReferences; } } public override AssemblySymbol ContainingAssembly { get { return _retargetingModule.ContainingAssembly; } } internal override ModuleSymbol ContainingModule { get { return _retargetingModule; } } public override bool IsGlobalNamespace { get { return _underlyingNamespace.IsGlobalNamespace; } } public override string Name { get { return _underlyingNamespace.Name; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingNamespace.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName) { // This method is invoked when looking up a type by metadata type // name through a RetargetingAssemblySymbol. For instance, in // UnitTests.Symbols.Metadata.PE.NoPia.LocalTypeSubstitution2. NamedTypeSymbol underlying = _underlyingNamespace.LookupMetadataType(ref typeName); Debug.Assert((object)underlying.ContainingModule == (object)_retargetingModule.UnderlyingModule); if (!underlying.IsErrorType() && underlying.IsExplicitDefinitionOfNoPiaLocalType) { // Explicitly defined local types should be hidden. return new MissingMetadataTypeSymbol.TopLevel(_retargetingModule, ref typeName); } return this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByName); } internal override void GetExtensionMethods(ArrayBuilder<MethodSymbol> methods, string nameOpt, int arity, LookupOptions options) { var underlyingMethods = ArrayBuilder<MethodSymbol>.GetInstance(); _underlyingNamespace.GetExtensionMethods(underlyingMethods, nameOpt, arity, options); foreach (var underlyingMethod in underlyingMethods) { methods.Add(this.RetargetingTranslator.Retarget(underlyingMethod)); } underlyingMethods.Free(); } internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness { get { return null; } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractImportCompletionProvider : LSPCompletionProvider { protected abstract Task<SyntaxContext> CreateContextAsync(Document document, int position, bool usePartialSemantic, CancellationToken cancellationToken); protected abstract ImmutableArray<string> GetImportedNamespaces(SyntaxNode location, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext); protected abstract Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespacesInScope, bool isExpandedCompletion, CancellationToken cancellationToken); protected abstract bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token); protected abstract Task<bool> ShouldProvideParenthesisCompletionAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); // For telemetry reporting protected abstract void LogCommit(); internal override bool IsExpandItemProvider => true; private bool? _isImportCompletionExperimentEnabled = null; private bool IsExperimentEnabled(Workspace workspace) { if (!_isImportCompletionExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isImportCompletionExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TypeImportCompletion); } return _isImportCompletionExperimentEnabled == true; } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { var cancellationToken = completionContext.CancellationToken; var document = completionContext.Document; // We need to check for context before option values, so we can tell completion service that we are in a context to provide expanded items // even though import completion might be disabled. This would show the expander in completion list which user can then use to explicitly ask for unimported items. var usePartialSemantic = completionContext.Options.GetOption(CompletionServiceOptions.UsePartialSemanticForImportCompletion); var syntaxContext = await CreateContextAsync(document, completionContext.Position, usePartialSemantic, cancellationToken).ConfigureAwait(false); if (!ShouldProvideCompletion(completionContext, syntaxContext)) { return; } completionContext.ExpandItemsAvailable = true; // We will trigger import completion regardless of the option/experiment if extended items is being requested explicitly (via expander in completion list) var isExpandedCompletion = completionContext.Options.GetOption(CompletionServiceOptions.IsExpandedCompletion); if (!isExpandedCompletion) { var importCompletionOptionValue = completionContext.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); // Don't trigger import completion if the option value is "default" and the experiment is disabled for the user. if (importCompletionOptionValue == false || (importCompletionOptionValue == null && !IsExperimentEnabled(document.Project.Solution.Workspace))) { return; } } // Find all namespaces in scope at current cursor location, // which will be used to filter so the provider only returns out-of-scope types. var namespacesInScope = GetNamespacesInScope(document, syntaxContext, cancellationToken); await AddCompletionItemsAsync(completionContext, syntaxContext, namespacesInScope, isExpandedCompletion, cancellationToken).ConfigureAwait(false); } private HashSet<string> GetNamespacesInScope(Document document, SyntaxContext syntaxContext, CancellationToken cancellationToken) { var semanticModel = syntaxContext.SemanticModel; // The location is the containing node of the LeftToken, or the compilation unit itsef if LeftToken // indicates the beginning of the document (i.e. no parent). var location = syntaxContext.LeftToken.Parent ?? syntaxContext.SyntaxTree.GetRoot(cancellationToken); var importedNamespaces = GetImportedNamespaces(location, semanticModel, cancellationToken); // This hashset will be used to match namespace names, so it must have the same case-sensitivity as the source language. var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespacesInScope = new HashSet<string>(importedNamespaces, syntaxFacts.StringComparer); // Get containing namespaces. var namespaceSymbol = semanticModel.GetEnclosingNamespace(syntaxContext.Position, cancellationToken); while (namespaceSymbol != null) { namespacesInScope.Add(namespaceSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat)); namespaceSymbol = namespaceSymbol.ContainingNamespace; } return namespacesInScope; } public override async Task<CompletionChange> GetChangeAsync( Document document, CompletionItem completionItem, char? commitKey, CancellationToken cancellationToken) { LogCommit(); var containingNamespace = ImportCompletionItem.GetContainingNamespace(completionItem); var provideParenthesisCompletion = await ShouldProvideParenthesisCompletionAsync( document, completionItem, commitKey, cancellationToken).ConfigureAwait(false); var insertText = completionItem.DisplayText; if (provideParenthesisCompletion) { insertText += "()"; CompletionProvidersLogger.LogCustomizedCommitToAddParenthesis(commitKey); } if (await ShouldCompleteWithFullyQualifyTypeName().ConfigureAwait(false)) { var completionText = $"{containingNamespace}.{insertText}"; return CompletionChange.Create(new TextChange(completionItem.Span, completionText)); } // Find context node so we can use it to decide where to insert using/imports. var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addImportContextNode = root.FindToken(completionItem.Span.Start, findInsideTrivia: true).Parent; // Add required using/imports directive. var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var importNode = CreateImport(document, containingNamespace); var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var rootWithImport = addImportService.AddImport(compilation, root, addImportContextNode!, importNode, generator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); var documentWithImport = document.WithSyntaxRoot(rootWithImport); // This only formats the annotated import we just added, not the entire document. var formattedDocumentWithImport = await Formatter.FormatAsync(documentWithImport, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<TextChange>.GetInstance(out var builder); // Get text change for add import var importChanges = await formattedDocumentWithImport.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false); builder.AddRange(importChanges); // Create text change for complete type name. // // Note: Don't try to obtain TextChange for completed type name by replacing the text directly, // then use Document.GetTextChangesAsync on document created from the changed text. This is // because it will do a diff and return TextChanges with minimum span instead of actual // replacement span. // // For example: If I'm typing "asd", the completion provider could be triggered after "a" // is typed. Then if I selected type "AsnEncodedData" to commit, by using the approach described // above, we will get a TextChange of "AsnEncodedDat" with 0 length span, instead of a change of // the full display text with a span of length 1. This will later mess up span-tracking and end up // with "AsnEncodedDatasd" in the code. builder.Add(new TextChange(completionItem.Span, insertText)); // Then get the combined change var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(builder); var changes = builder.ToImmutable(); var change = Utilities.Collapse(newText, changes); return CompletionChange.Create(change, changes); async Task<bool> ShouldCompleteWithFullyQualifyTypeName() { if (!IsAddingImportsSupported(document)) { return true; } // We might need to qualify unimported types to use them in an import directive, because they only affect members of the containing // import container (e.g. namespace/class/etc. declarations). // // For example, `List` and `StringBuilder` both need to be fully qualified below: // // using CollectionOfStringBuilders = System.Collections.Generic.List<System.Text.StringBuilder>; // // However, if we are typing in an C# using directive that is inside a nested import container (i.e. inside a namespace declaration block), // then we can add an using in the outer import container instead (this is not allowed in VB). // // For example: // // using System.Collections.Generic; // using System.Text; // // namespace Foo // { // using CollectionOfStringBuilders = List<StringBuilder>; // } // // Here we will always choose to qualify the unimported type, just to be consistent and keeps things simple. return await IsInImportsDirectiveAsync(document, completionItem.Span.Start, cancellationToken).ConfigureAwait(false); } } private async Task<bool> IsInImportsDirectiveAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); return leftToken.GetAncestor(syntaxFacts.IsUsingOrExternOrImport) is { } node && !IsFinalSemicolonOfUsingOrExtern(node, leftToken); } protected static bool IsAddingImportsSupported(Document document) { var workspace = document.Project.Solution.Workspace; // Certain types of workspace don't support document change, e.g. DebuggerIntelliSenseWorkspace if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return false; } // Certain documents, e.g. Razor document, don't support adding imports var documentSupportsFeatureService = workspace.Services.GetRequiredService<IDocumentSupportsFeatureService>(); if (!documentSupportsFeatureService.SupportsRefactorings(document)) { return false; } return true; } private static SyntaxNode CreateImport(Document document, string namespaceName) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); return syntaxGenerator.NamespaceImportDeclaration(namespaceName).WithAdditionalAnnotations(Formatter.Annotation); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => ImportCompletionItem.GetCompletionDescriptionAsync(document, item, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract class AbstractImportCompletionProvider : LSPCompletionProvider { protected abstract Task<SyntaxContext> CreateContextAsync(Document document, int position, bool usePartialSemantic, CancellationToken cancellationToken); protected abstract ImmutableArray<string> GetImportedNamespaces(SyntaxNode location, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract bool ShouldProvideCompletion(CompletionContext completionContext, SyntaxContext syntaxContext); protected abstract Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, HashSet<string> namespacesInScope, bool isExpandedCompletion, CancellationToken cancellationToken); protected abstract bool IsFinalSemicolonOfUsingOrExtern(SyntaxNode directive, SyntaxToken token); protected abstract Task<bool> ShouldProvideParenthesisCompletionAsync(Document document, CompletionItem item, char? commitKey, CancellationToken cancellationToken); // For telemetry reporting protected abstract void LogCommit(); internal override bool IsExpandItemProvider => true; private bool? _isImportCompletionExperimentEnabled = null; private bool IsExperimentEnabled(Workspace workspace) { if (!_isImportCompletionExperimentEnabled.HasValue) { var experimentationService = workspace.Services.GetRequiredService<IExperimentationService>(); _isImportCompletionExperimentEnabled = experimentationService.IsExperimentEnabled(WellKnownExperimentNames.TypeImportCompletion); } return _isImportCompletionExperimentEnabled == true; } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { var cancellationToken = completionContext.CancellationToken; var document = completionContext.Document; // We need to check for context before option values, so we can tell completion service that we are in a context to provide expanded items // even though import completion might be disabled. This would show the expander in completion list which user can then use to explicitly ask for unimported items. var usePartialSemantic = completionContext.Options.GetOption(CompletionServiceOptions.UsePartialSemanticForImportCompletion); var syntaxContext = await CreateContextAsync(document, completionContext.Position, usePartialSemantic, cancellationToken).ConfigureAwait(false); if (!ShouldProvideCompletion(completionContext, syntaxContext)) { return; } completionContext.ExpandItemsAvailable = true; // We will trigger import completion regardless of the option/experiment if extended items is being requested explicitly (via expander in completion list) var isExpandedCompletion = completionContext.Options.GetOption(CompletionServiceOptions.IsExpandedCompletion); if (!isExpandedCompletion) { var importCompletionOptionValue = completionContext.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); // Don't trigger import completion if the option value is "default" and the experiment is disabled for the user. if (importCompletionOptionValue == false || (importCompletionOptionValue == null && !IsExperimentEnabled(document.Project.Solution.Workspace))) { return; } } // Find all namespaces in scope at current cursor location, // which will be used to filter so the provider only returns out-of-scope types. var namespacesInScope = GetNamespacesInScope(document, syntaxContext, cancellationToken); await AddCompletionItemsAsync(completionContext, syntaxContext, namespacesInScope, isExpandedCompletion, cancellationToken).ConfigureAwait(false); } private HashSet<string> GetNamespacesInScope(Document document, SyntaxContext syntaxContext, CancellationToken cancellationToken) { var semanticModel = syntaxContext.SemanticModel; // The location is the containing node of the LeftToken, or the compilation unit itsef if LeftToken // indicates the beginning of the document (i.e. no parent). var location = syntaxContext.LeftToken.Parent ?? syntaxContext.SyntaxTree.GetRoot(cancellationToken); var importedNamespaces = GetImportedNamespaces(location, semanticModel, cancellationToken); // This hashset will be used to match namespace names, so it must have the same case-sensitivity as the source language. var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespacesInScope = new HashSet<string>(importedNamespaces, syntaxFacts.StringComparer); // Get containing namespaces. var namespaceSymbol = semanticModel.GetEnclosingNamespace(syntaxContext.Position, cancellationToken); while (namespaceSymbol != null) { namespacesInScope.Add(namespaceSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat)); namespaceSymbol = namespaceSymbol.ContainingNamespace; } return namespacesInScope; } public override async Task<CompletionChange> GetChangeAsync( Document document, CompletionItem completionItem, char? commitKey, CancellationToken cancellationToken) { LogCommit(); var containingNamespace = ImportCompletionItem.GetContainingNamespace(completionItem); var provideParenthesisCompletion = await ShouldProvideParenthesisCompletionAsync( document, completionItem, commitKey, cancellationToken).ConfigureAwait(false); var insertText = completionItem.DisplayText; if (provideParenthesisCompletion) { insertText += "()"; CompletionProvidersLogger.LogCustomizedCommitToAddParenthesis(commitKey); } if (await ShouldCompleteWithFullyQualifyTypeName().ConfigureAwait(false)) { var completionText = $"{containingNamespace}.{insertText}"; return CompletionChange.Create(new TextChange(completionItem.Span, completionText)); } // Find context node so we can use it to decide where to insert using/imports. var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addImportContextNode = root.FindToken(completionItem.Span.Start, findInsideTrivia: true).Parent; // Add required using/imports directive. var addImportService = document.GetRequiredLanguageService<IAddImportsService>(); var generator = document.GetRequiredLanguageService<SyntaxGenerator>(); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var allowInHiddenRegions = document.CanAddImportsInHiddenRegions(); var importNode = CreateImport(document, containingNamespace); var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var rootWithImport = addImportService.AddImport(compilation, root, addImportContextNode!, importNode, generator, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken); var documentWithImport = document.WithSyntaxRoot(rootWithImport); // This only formats the annotated import we just added, not the entire document. var formattedDocumentWithImport = await Formatter.FormatAsync(documentWithImport, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); using var _ = ArrayBuilder<TextChange>.GetInstance(out var builder); // Get text change for add import var importChanges = await formattedDocumentWithImport.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false); builder.AddRange(importChanges); // Create text change for complete type name. // // Note: Don't try to obtain TextChange for completed type name by replacing the text directly, // then use Document.GetTextChangesAsync on document created from the changed text. This is // because it will do a diff and return TextChanges with minimum span instead of actual // replacement span. // // For example: If I'm typing "asd", the completion provider could be triggered after "a" // is typed. Then if I selected type "AsnEncodedData" to commit, by using the approach described // above, we will get a TextChange of "AsnEncodedDat" with 0 length span, instead of a change of // the full display text with a span of length 1. This will later mess up span-tracking and end up // with "AsnEncodedDatasd" in the code. builder.Add(new TextChange(completionItem.Span, insertText)); // Then get the combined change var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(builder); var changes = builder.ToImmutable(); var change = Utilities.Collapse(newText, changes); return CompletionChange.Create(change, changes); async Task<bool> ShouldCompleteWithFullyQualifyTypeName() { if (!IsAddingImportsSupported(document)) { return true; } // We might need to qualify unimported types to use them in an import directive, because they only affect members of the containing // import container (e.g. namespace/class/etc. declarations). // // For example, `List` and `StringBuilder` both need to be fully qualified below: // // using CollectionOfStringBuilders = System.Collections.Generic.List<System.Text.StringBuilder>; // // However, if we are typing in an C# using directive that is inside a nested import container (i.e. inside a namespace declaration block), // then we can add an using in the outer import container instead (this is not allowed in VB). // // For example: // // using System.Collections.Generic; // using System.Text; // // namespace Foo // { // using CollectionOfStringBuilders = List<StringBuilder>; // } // // Here we will always choose to qualify the unimported type, just to be consistent and keeps things simple. return await IsInImportsDirectiveAsync(document, completionItem.Span.Start, cancellationToken).ConfigureAwait(false); } } private async Task<bool> IsInImportsDirectiveAsync(Document document, int position, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxTree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); return leftToken.GetAncestor(syntaxFacts.IsUsingOrExternOrImport) is { } node && !IsFinalSemicolonOfUsingOrExtern(node, leftToken); } protected static bool IsAddingImportsSupported(Document document) { var workspace = document.Project.Solution.Workspace; // Certain types of workspace don't support document change, e.g. DebuggerIntelliSenseWorkspace if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { return false; } // Certain documents, e.g. Razor document, don't support adding imports var documentSupportsFeatureService = workspace.Services.GetRequiredService<IDocumentSupportsFeatureService>(); if (!documentSupportsFeatureService.SupportsRefactorings(document)) { return false; } return true; } private static SyntaxNode CreateImport(Document document, string namespaceName) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); return syntaxGenerator.NamespaceImportDeclaration(namespaceName).WithAdditionalAnnotations(Formatter.Annotation); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => ImportCompletionItem.GetCompletionDescriptionAsync(document, item, cancellationToken); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/MSBuild/MSBuild/Constants/MetadataNames.cs
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal static class MetadataNames { public const string Aliases = nameof(Aliases); public const string HintPath = nameof(HintPath); public const string Link = nameof(Link); public const string Name = nameof(Name); public const string ReferenceOutputAssembly = nameof(ReferenceOutputAssembly); } }
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal static class MetadataNames { public const string Aliases = nameof(Aliases); public const string HintPath = nameof(HintPath); public const string Link = nameof(Link); public const string Name = nameof(Name); public const string ReferenceOutputAssembly = nameof(ReferenceOutputAssembly); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/InlineRename/AbstractInlineRenameUndoManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// This class contains the logic common to VS and ETA when implementing IInlineRenameUndoManager /// </summary> internal abstract class AbstractInlineRenameUndoManager<TBufferState> { protected class ActiveSpanState { public string ReplacementText; public int SelectionAnchorPoint; public int SelectionActivePoint; } protected readonly InlineRenameService InlineRenameService; protected readonly Dictionary<ITextBuffer, TBufferState> UndoManagers = new Dictionary<ITextBuffer, TBufferState>(); protected readonly Stack<ActiveSpanState> UndoStack = new Stack<ActiveSpanState>(); protected readonly Stack<ActiveSpanState> RedoStack = new Stack<ActiveSpanState>(); protected ActiveSpanState initialState; protected ActiveSpanState currentState; protected bool updatePending = false; public AbstractInlineRenameUndoManager(InlineRenameService inlineRenameService) => this.InlineRenameService = inlineRenameService; public void Disconnect() { this.UndoManagers.Clear(); this.UndoStack.Clear(); this.RedoStack.Clear(); this.initialState = null; this.currentState = null; } private void UpdateCurrentState(string replacementText, ITextSelection selection, SnapshotSpan activeSpan) { var snapshot = activeSpan.Snapshot; var selectionSpan = selection.GetSnapshotSpansOnBuffer(snapshot.TextBuffer).Single(); var start = selectionSpan.Start.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; var end = selectionSpan.End.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; this.currentState = new ActiveSpanState() { ReplacementText = replacementText, SelectionAnchorPoint = selection.IsReversed ? end : start, SelectionActivePoint = selection.IsReversed ? start : end }; } public void CreateInitialState(string replacementText, ITextSelection selection, SnapshotSpan startingSpan) { UpdateCurrentState(replacementText, selection, startingSpan); this.initialState = this.currentState; } public void OnTextChanged(ITextSelection selection, SnapshotSpan singleTrackingSpanTouched) { this.RedoStack.Clear(); if (!this.UndoStack.Any()) { this.UndoStack.Push(this.initialState); } // For now, we will only ever be one Undo away from the beginning of the rename session. We can // implement Undo merging in the future. var replacementText = singleTrackingSpanTouched.GetText(); UpdateCurrentState(replacementText, selection, singleTrackingSpanTouched); this.InlineRenameService.ActiveSession.ApplyReplacementText(replacementText, propagateEditImmediately: false); } public void UpdateSelection(ITextView textView, ITextBuffer subjectBuffer, ITrackingSpan activeRenameSpan) { var snapshot = subjectBuffer.CurrentSnapshot; var anchor = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionAnchorPoint + activeRenameSpan.GetStartPoint(snapshot)); var active = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionActivePoint + activeRenameSpan.GetStartPoint(snapshot)); textView.SetSelection(anchor, active); } public void Undo(ITextBuffer _) { if (this.UndoStack.Count > 0) { this.RedoStack.Push(this.currentState); this.currentState = this.UndoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } else { this.InlineRenameService.ActiveSession.Cancel(); } } public void Redo(ITextBuffer _) { if (this.RedoStack.Count > 0) { this.UndoStack.Push(this.currentState); this.currentState = this.RedoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } } protected abstract void UndoTemporaryEdits(ITextBuffer subjectBuffer, bool disconnect, bool undoConflictResolution); protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory undoHistory, object propagateSpansEditTag, IEnumerable<ITrackingSpan> spans, string replacementText) { // roll back to the initial state for the buffer after conflict resolution this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty); using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText)); using var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag); foreach (var span in spans) { if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText) { edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText); } } edit.ApplyAndLogExceptions(); if (!edit.HasEffectiveChanges && !this.UndoStack.Any()) { transaction.Cancel(); } else { transaction.Complete(); } } protected static string GetUndoTransactionDescription(string replacementText) => replacementText == string.Empty ? "Delete Text" : replacementText; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// This class contains the logic common to VS and ETA when implementing IInlineRenameUndoManager /// </summary> internal abstract class AbstractInlineRenameUndoManager<TBufferState> { protected class ActiveSpanState { public string ReplacementText; public int SelectionAnchorPoint; public int SelectionActivePoint; } protected readonly InlineRenameService InlineRenameService; protected readonly Dictionary<ITextBuffer, TBufferState> UndoManagers = new Dictionary<ITextBuffer, TBufferState>(); protected readonly Stack<ActiveSpanState> UndoStack = new Stack<ActiveSpanState>(); protected readonly Stack<ActiveSpanState> RedoStack = new Stack<ActiveSpanState>(); protected ActiveSpanState initialState; protected ActiveSpanState currentState; protected bool updatePending = false; public AbstractInlineRenameUndoManager(InlineRenameService inlineRenameService) => this.InlineRenameService = inlineRenameService; public void Disconnect() { this.UndoManagers.Clear(); this.UndoStack.Clear(); this.RedoStack.Clear(); this.initialState = null; this.currentState = null; } private void UpdateCurrentState(string replacementText, ITextSelection selection, SnapshotSpan activeSpan) { var snapshot = activeSpan.Snapshot; var selectionSpan = selection.GetSnapshotSpansOnBuffer(snapshot.TextBuffer).Single(); var start = selectionSpan.Start.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; var end = selectionSpan.End.TranslateTo(snapshot, PointTrackingMode.Positive).Position - activeSpan.Start.Position; this.currentState = new ActiveSpanState() { ReplacementText = replacementText, SelectionAnchorPoint = selection.IsReversed ? end : start, SelectionActivePoint = selection.IsReversed ? start : end }; } public void CreateInitialState(string replacementText, ITextSelection selection, SnapshotSpan startingSpan) { UpdateCurrentState(replacementText, selection, startingSpan); this.initialState = this.currentState; } public void OnTextChanged(ITextSelection selection, SnapshotSpan singleTrackingSpanTouched) { this.RedoStack.Clear(); if (!this.UndoStack.Any()) { this.UndoStack.Push(this.initialState); } // For now, we will only ever be one Undo away from the beginning of the rename session. We can // implement Undo merging in the future. var replacementText = singleTrackingSpanTouched.GetText(); UpdateCurrentState(replacementText, selection, singleTrackingSpanTouched); this.InlineRenameService.ActiveSession.ApplyReplacementText(replacementText, propagateEditImmediately: false); } public void UpdateSelection(ITextView textView, ITextBuffer subjectBuffer, ITrackingSpan activeRenameSpan) { var snapshot = subjectBuffer.CurrentSnapshot; var anchor = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionAnchorPoint + activeRenameSpan.GetStartPoint(snapshot)); var active = new VirtualSnapshotPoint(snapshot, this.currentState.SelectionActivePoint + activeRenameSpan.GetStartPoint(snapshot)); textView.SetSelection(anchor, active); } public void Undo(ITextBuffer _) { if (this.UndoStack.Count > 0) { this.RedoStack.Push(this.currentState); this.currentState = this.UndoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } else { this.InlineRenameService.ActiveSession.Cancel(); } } public void Redo(ITextBuffer _) { if (this.RedoStack.Count > 0) { this.UndoStack.Push(this.currentState); this.currentState = this.RedoStack.Pop(); this.InlineRenameService.ActiveSession.ApplyReplacementText(this.currentState.ReplacementText, propagateEditImmediately: true); } } protected abstract void UndoTemporaryEdits(ITextBuffer subjectBuffer, bool disconnect, bool undoConflictResolution); protected void ApplyReplacementText(ITextBuffer subjectBuffer, ITextUndoHistory undoHistory, object propagateSpansEditTag, IEnumerable<ITrackingSpan> spans, string replacementText) { // roll back to the initial state for the buffer after conflict resolution this.UndoTemporaryEdits(subjectBuffer, disconnect: false, undoConflictResolution: replacementText == string.Empty); using var transaction = undoHistory.CreateTransaction(GetUndoTransactionDescription(replacementText)); using var edit = subjectBuffer.CreateEdit(EditOptions.None, null, propagateSpansEditTag); foreach (var span in spans) { if (span.GetText(subjectBuffer.CurrentSnapshot) != replacementText) { edit.Replace(span.GetSpan(subjectBuffer.CurrentSnapshot), replacementText); } } edit.ApplyAndLogExceptions(); if (!edit.HasEffectiveChanges && !this.UndoStack.Any()) { transaction.Cancel(); } else { transaction.Complete(); } } protected static string GetUndoTransactionDescription(string replacementText) => replacementText == string.Empty ? "Delete Text" : replacementText; } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/CodeActions/Operations/ApplyChangesOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// A <see cref="CodeActionOperation"/> for applying solution changes to a workspace. /// <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/> may return at most one /// <see cref="ApplyChangesOperation"/>. Hosts may provide custom handling for /// <see cref="ApplyChangesOperation"/>s, but if a <see cref="CodeAction"/> requires custom /// host behavior not supported by a single <see cref="ApplyChangesOperation"/>, then instead: /// <list type="bullet"> /// <description><text>Implement a custom <see cref="CodeAction"/> and <see cref="CodeActionOperation"/>s</text></description> /// <description><text>Do not return any <see cref="ApplyChangesOperation"/> from <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/></text></description> /// <description><text>Directly apply any workspace edits</text></description> /// <description><text>Handle any custom host behavior</text></description> /// <description><text>Produce a preview for <see cref="CodeAction.GetPreviewOperationsAsync(CancellationToken)"/> /// by creating a custom <see cref="PreviewOperation"/> or returning a single <see cref="ApplyChangesOperation"/> /// to use the built-in preview mechanism</text></description> /// </list> /// </summary> public sealed class ApplyChangesOperation : CodeActionOperation { public Solution ChangedSolution { get; } public ApplyChangesOperation(Solution changedSolution) => ChangedSolution = changedSolution ?? throw new ArgumentNullException(nameof(changedSolution)); internal override bool ApplyDuringTests => true; public override void Apply(Workspace workspace, CancellationToken cancellationToken) => this.TryApply(workspace, new ProgressTracker(), cancellationToken); internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return workspace.TryApplyChanges(ChangedSolution, progressTracker); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// A <see cref="CodeActionOperation"/> for applying solution changes to a workspace. /// <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/> may return at most one /// <see cref="ApplyChangesOperation"/>. Hosts may provide custom handling for /// <see cref="ApplyChangesOperation"/>s, but if a <see cref="CodeAction"/> requires custom /// host behavior not supported by a single <see cref="ApplyChangesOperation"/>, then instead: /// <list type="bullet"> /// <description><text>Implement a custom <see cref="CodeAction"/> and <see cref="CodeActionOperation"/>s</text></description> /// <description><text>Do not return any <see cref="ApplyChangesOperation"/> from <see cref="CodeAction.GetOperationsAsync(CancellationToken)"/></text></description> /// <description><text>Directly apply any workspace edits</text></description> /// <description><text>Handle any custom host behavior</text></description> /// <description><text>Produce a preview for <see cref="CodeAction.GetPreviewOperationsAsync(CancellationToken)"/> /// by creating a custom <see cref="PreviewOperation"/> or returning a single <see cref="ApplyChangesOperation"/> /// to use the built-in preview mechanism</text></description> /// </list> /// </summary> public sealed class ApplyChangesOperation : CodeActionOperation { public Solution ChangedSolution { get; } public ApplyChangesOperation(Solution changedSolution) => ChangedSolution = changedSolution ?? throw new ArgumentNullException(nameof(changedSolution)); internal override bool ApplyDuringTests => true; public override void Apply(Workspace workspace, CancellationToken cancellationToken) => this.TryApply(workspace, new ProgressTracker(), cancellationToken); internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return workspace.TryApplyChanges(ChangedSolution, progressTracker); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Classification/CopyPasteAndPrintingClassifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Classification)] public class CopyPasteAndPrintingClassifierTests { [WpfFact] public async Task TestGetTagsOnBufferTagger() { // don't crash using var workspace = TestWorkspace.CreateCSharp("class C { C c; }"); var document = workspace.Documents.First(); var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var provider = new CopyPasteAndPrintingClassificationBufferTaggerProvider( workspace.ExportProvider.GetExportedValue<IThreadingContext>(), workspace.ExportProvider.GetExportedValue<ClassificationTypeMap>(), listenerProvider); var tagger = provider.CreateTagger<IClassificationTag>(document.GetTextBuffer())!; using var disposable = (IDisposable)tagger; var waiter = listenerProvider.GetWaiter(FeatureAttribute.Classification); await waiter.ExpeditedWaitAsync(); var tags = tagger.GetTags(document.GetTextBuffer().CurrentSnapshot.GetSnapshotSpanCollection()); var allTags = tagger.GetAllTags(document.GetTextBuffer().CurrentSnapshot.GetSnapshotSpanCollection(), CancellationToken.None); Assert.Empty(tags); Assert.NotEmpty(allTags); Assert.Equal(1, allTags.Count()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Classification)] public class CopyPasteAndPrintingClassifierTests { [WpfFact] public async Task TestGetTagsOnBufferTagger() { // don't crash using var workspace = TestWorkspace.CreateCSharp("class C { C c; }"); var document = workspace.Documents.First(); var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var provider = new CopyPasteAndPrintingClassificationBufferTaggerProvider( workspace.ExportProvider.GetExportedValue<IThreadingContext>(), workspace.ExportProvider.GetExportedValue<ClassificationTypeMap>(), listenerProvider); var tagger = provider.CreateTagger<IClassificationTag>(document.GetTextBuffer())!; using var disposable = (IDisposable)tagger; var waiter = listenerProvider.GetWaiter(FeatureAttribute.Classification); await waiter.ExpeditedWaitAsync(); var tags = tagger.GetTags(document.GetTextBuffer().CurrentSnapshot.GetSnapshotSpanCollection()); var allTags = tagger.GetAllTags(document.GetTextBuffer().CurrentSnapshot.GetSnapshotSpanCollection(), CancellationToken.None); Assert.Empty(tags); Assert.NotEmpty(allTags); Assert.Equal(1, allTags.Count()); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Test/ProjectSystemShim/TempPECompilerServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { public class TempPECompilerServiceTests { [Fact] public void TempPECompilationWithInvalidReferenceDoesNotCrash() { var tempPEService = new TempPECompilerService(new TrivialMetadataService()); using var tempRoot = new TempRoot(); var directory = tempRoot.CreateDirectory(); // This should not crash. Visual inspection of the Dev12 codebase implied we might return // S_FALSE in this case, but it wasn't very clear. In any case, it's not expected to throw,m // so S_FALSE seems fine. var hr = tempPEService.CompileTempPE( pszOutputFileName: Path.Combine(directory.Path, "Output.dll"), sourceCount: 0, fileNames: Array.Empty<string>(), fileContents: Array.Empty<string>(), optionCount: 1, optionNames: new[] { "r" }, optionValues: new[] { Path.Combine(directory.Path, "MissingReference.dll") }); Assert.Equal(VSConstants.S_FALSE, hr); } private class TrivialMetadataService : IMetadataService { public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties) { return MetadataReference.CreateFromFile(resolvedPath, properties); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { public class TempPECompilerServiceTests { [Fact] public void TempPECompilationWithInvalidReferenceDoesNotCrash() { var tempPEService = new TempPECompilerService(new TrivialMetadataService()); using var tempRoot = new TempRoot(); var directory = tempRoot.CreateDirectory(); // This should not crash. Visual inspection of the Dev12 codebase implied we might return // S_FALSE in this case, but it wasn't very clear. In any case, it's not expected to throw,m // so S_FALSE seems fine. var hr = tempPEService.CompileTempPE( pszOutputFileName: Path.Combine(directory.Path, "Output.dll"), sourceCount: 0, fileNames: Array.Empty<string>(), fileContents: Array.Empty<string>(), optionCount: 1, optionNames: new[] { "r" }, optionValues: new[] { Path.Combine(directory.Path, "MissingReference.dll") }); Assert.Equal(VSConstants.S_FALSE, hr); } private class TrivialMetadataService : IMetadataService { public PortableExecutableReference GetReference(string resolvedPath, MetadataReferenceProperties properties) { return MetadataReference.CreateFromFile(resolvedPath, properties); } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Remote/ServiceHub/Services/ProjectTelemetry/ApiUsageIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/Analyzers/FaultyAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Build FaultyAnalyzer.dll with: csc.exe /t:library FaultyAnalyzer.cs /r:Microsoft.CodeAnalysis.dll /r:System.Runtime.dll using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Build FaultyAnalyzer.dll with: csc.exe /t:library FaultyAnalyzer.cs /r:Microsoft.CodeAnalysis.dll /r:System.Runtime.dll using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public abstract class TestAnalyzer : DiagnosticAnalyzer { }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/TodoComments/ITodoCommentsListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Callback the host (VS) passes to the OOP service to allow it to send batch notifications about todo comments. /// </summary> internal interface ITodoCommentsListener { ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// Callback the host (VS) passes to the OOP service to allow it to send batch notifications about todo comments. /// </summary> internal interface ITodoCommentsListener { ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/TokenComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class TokenComparer : IComparer<SyntaxToken> { public static readonly IComparer<SyntaxToken> NormalInstance = new TokenComparer(specialCaseSystem: false); public static readonly IComparer<SyntaxToken> SystemFirstInstance = new TokenComparer(specialCaseSystem: true); private readonly bool _specialCaseSystem; private TokenComparer(bool specialCaseSystem) => _specialCaseSystem = specialCaseSystem; public int Compare(SyntaxToken x, SyntaxToken y) { if (_specialCaseSystem && x.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword) && y.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword)) { var token1IsSystem = x.ValueText == nameof(System); var token2IsSystem = y.ValueText == nameof(System); if (token1IsSystem && !token2IsSystem) { return -1; } else if (!token1IsSystem && token2IsSystem) { return 1; } } return CompareWorker(x, y); } private static int CompareWorker(SyntaxToken x, SyntaxToken y) { if (x == y) { return 0; } // 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. var string1 = x.ValueText; var string2 = y.ValueText; // First check in a case insensitive manner. This will put // everything that starts with an 'a' or 'A' above everything // that starts with a 'b' or 'B'. var compare = CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth); if (compare != 0) { return compare; } // Now, once we've grouped such that 'a' words and 'A' words are // together, sort such that 'a' words come before 'A' words. return CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Microsoft.CodeAnalysis.CSharp.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class TokenComparer : IComparer<SyntaxToken> { public static readonly IComparer<SyntaxToken> NormalInstance = new TokenComparer(specialCaseSystem: false); public static readonly IComparer<SyntaxToken> SystemFirstInstance = new TokenComparer(specialCaseSystem: true); private readonly bool _specialCaseSystem; private TokenComparer(bool specialCaseSystem) => _specialCaseSystem = specialCaseSystem; public int Compare(SyntaxToken x, SyntaxToken y) { if (_specialCaseSystem && x.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword) && y.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword, SyntaxKind.StaticKeyword)) { var token1IsSystem = x.ValueText == nameof(System); var token2IsSystem = y.ValueText == nameof(System); if (token1IsSystem && !token2IsSystem) { return -1; } else if (!token1IsSystem && token2IsSystem) { return 1; } } return CompareWorker(x, y); } private static int CompareWorker(SyntaxToken x, SyntaxToken y) { if (x == y) { return 0; } // 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. var string1 = x.ValueText; var string2 = y.ValueText; // First check in a case insensitive manner. This will put // everything that starts with an 'a' or 'A' above everything // that starts with a 'b' or 'B'. var compare = CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth); if (compare != 0) { return compare; } // Now, once we've grouped such that 'a' words and 'A' words are // together, sort such that 'a' words come before 'A' words. return CultureInfo.InvariantCulture.CompareInfo.Compare(string1, string2, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/PDB/PDBDynamicLocalsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBDynamicLocalsTests : CSharpTestBase { [Fact] public void EmitPDBDynamicObjectVariable1() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { dynamic d1 = new Helper(); dynamic d2 = new Point(); D d4 = new D(d1.goo); Helper d5 = new Helper(d1); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { CSharpRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> <bucket flags=""1"" slotId=""1"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""0"" offset=""98"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""28"" document=""1"" /> <entry offset=""0x17"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""24"" document=""1"" /> <entry offset=""0xb1"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""30"" document=""1"" /> <entry offset=""0x10f"" startLine=""24"" startColumn=""3"" endLine=""24"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x110""> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d2"" il_index=""1"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d4"" il_index=""2"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d5"" il_index=""3"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocals1() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic[] arrDynamic = new dynamic[] {""1""}; foreach (dynamic d in arrDynamic) { //do nothing } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""1"" slotId=""3"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""6"" offset=""58"" /> <slot kind=""8"" offset=""58"" /> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""46"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""31"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""28"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <local name=""arrDynamic"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <local name=""d"" il_index=""3"" il_start=""0x17"" il_end=""0x1d"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicConstVariable() { string source = @" class Test { public static void Main(string[] args) { { const dynamic d = null; const string c = null; } { const dynamic c = null; const dynamic d = null; } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""c"" /> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""d"" value=""null"" type=""Object"" /> <constant name=""c"" value=""null"" type=""String"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""c"" value=""null"" type=""Object"" /> <constant name=""d"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicDuplicateName() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { { dynamic a = null; object b = null; } { dynamic[] a = null; dynamic b = null; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""a"" /> <bucket flags=""01"" slotId=""2"" localName=""a"" /> <bucket flags=""1"" slotId=""3"" localName=""b"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""119"" /> <slot kind=""0"" offset=""150"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""30"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <scope startOffset=""0x1"" endOffset=""0x7""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> </scope> <scope startOffset=""0x7"" endOffset=""0xd""> <local name=""a"" il_index=""2"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> <local name=""b"" il_index=""3"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicVariableNameTooLong() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d12345678901234567890123456789012345678901234567890123456789012"" /> <bucket flags=""1"" slotId=""0"" localName=""b12345678901234567890123456789012345678901234567890123456789012"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""234"" /> <slot kind=""0"" offset=""336"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""89"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""88"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <local name=""c123456789012345678901234567890123456789012345678901234567890123"" il_index=""0"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <local name=""d12345678901234567890123456789012345678901234567890123456789012"" il_index=""1"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <constant name=""a123456789012345678901234567890123456789012345678901234567890123"" value=""null"" type=""Object"" /> <constant name=""b12345678901234567890123456789012345678901234567890123456789012"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicArrayVariable() { string source = WithWindowsLineBreaks(@" class ArrayTest { int x; } class Test { public static void Main(string[] args) { dynamic[] arr = new dynamic[10]; dynamic[,] arrdim = new string[2,3]; dynamic[] arrobj = new ArrayTest[2]; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arr"" /> <bucket flags=""01"" slotId=""1"" localName=""arrdim"" /> <bucket flags=""01"" slotId=""2"" localName=""arrobj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""91"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1e"" startLine=""13"" startColumn=""3"" endLine=""13"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <local name=""arr"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrdim"" il_index=""1"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrobj"" il_index=""2"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicCollectionVariable() { string source = WithWindowsLineBreaks(@" using System.Collections.Generic; class Test { public static void Main(string[] args) { dynamic l1 = new List<int>(); List<dynamic> l2 = new List<dynamic>(); dynamic l3 = new List<dynamic>(); Dictionary<dynamic,dynamic> d1 = new Dictionary<dynamic,dynamic>(); dynamic d2 = new Dictionary<int,int>(); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""l1"" /> <bucket flags=""01"" slotId=""1"" localName=""l2"" /> <bucket flags=""1"" slotId=""2"" localName=""l3"" /> <bucket flags=""011"" slotId=""3"" localName=""d1"" /> <bucket flags=""1"" slotId=""4"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""146"" /> <slot kind=""0"" offset=""197"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""3"" endLine=""6"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""32"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""42"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <namespace name=""System.Collections.Generic"" /> <local name=""l1"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l2"" il_index=""1"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l3"" il_index=""2"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d1"" il_index=""3"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d2"" il_index=""4"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBDynamicObjectVariable2() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { Helper staticObj = new Helper(); dynamic d1 = new Helper(); dynamic d3 = new D(staticObj.goo); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d1"" /> <bucket flags=""1"" slotId=""2"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> <slot kind=""0"" offset=""49"" /> <slot kind=""0"" offset=""79"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""29"" document=""1"" /> <entry offset=""0xd"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""37"" document=""1"" /> <entry offset=""0x1a"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""staticObj"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d1"" il_index=""1"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d3"" il_index=""2"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassConstructorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { public Test() { dynamic d; } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""2"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""d"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassPropertyDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { string field; public dynamic Field { get { dynamic d = field + field; return d; } set { dynamic d = null; //field = d; Not yet implemented in Roslyn } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Field""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Field"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x3"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassOverloadedOperatorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Complex { int real; int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static dynamic operator +(Complex c1, Complex c2) { dynamic d = new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); return d; } } class Test { public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Complex"" name="".ctor"" parameterNames=""real, imaginary""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Complex"" name=""op_Addition"" parameterNames=""c1, c2""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""81"" document=""1"" /> <entry offset=""0x21"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0x25"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassIndexerDynamicLocal() { string source = WithWindowsLineBreaks(@" class Test { dynamic[] arr; public dynamic this[int i] { get { dynamic d = arr[i]; return d; } set { dynamic d = (dynamic) value; arr[i] = d; } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x10"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Item"" parameterNames=""i, value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""41"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0xc"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassEventHandlerDynamicLocal() { string source = WithWindowsLineBreaks(@" using System; class Sample { public static void Main() { ConsoleKeyInfo cki; Console.Clear(); Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); } protected static void myHandler(object sender, ConsoleCancelEventArgs args) { dynamic d; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Sample"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""26"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""76"" document=""1"" /> <entry offset=""0x19"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""cki"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> <method containingType=""Sample"" name=""myHandler"" parameterNames=""sender, args""> <customDebugInfo> <forward declaringType=""Sample"" methodName=""Main"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBStructDynamicLocals() { string source = WithWindowsLineBreaks(@" using System; struct Test { int d; public Test(int d) { dynamic d1; this.d = d; } public int D { get { dynamic d2; return d; } set { dynamic d3; d = value; } } public static Test operator +(Test t1, Test t2) { dynamic d4; return new Test(t1.d + t2.d); } public static void Main() { dynamic d5; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor"" parameterNames=""d""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""get_D""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <local name=""d2"" il_index=""0"" il_start=""0x0"" il_end=""0xc"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_D"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""d3"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""op_Addition"" parameterNames=""t1, t2""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d4"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""38"" document=""1"" /> <entry offset=""0x16"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x18""> <local name=""d4"" il_index=""0"" il_start=""0x0"" il_end=""0x18"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBAnonymousFunctionLocals() { string source = WithWindowsLineBreaks(@" using System; class Test { public delegate dynamic D1(dynamic d1); public delegate void D2(dynamic d2); public static void Main(string[] args) { D1 obj1 = d3 => d3; D2 obj2 = new D2(d4 => { dynamic d5; d5 = d4; }); D1 obj3 = (dynamic d6) => { return d6; }; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""14"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""102"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset=""27"" /> <lambda offset=""63"" /> <lambda offset=""125"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""50"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <namespace name=""System"" /> <local name=""obj1"" il_index=""0"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj2"" il_index=""1"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj3"" il_index=""2"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_0"" parameterNames=""d3""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_1"" parameterNames=""d4""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""73"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""32"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""46"" endLine=""10"" endColumn=""54"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""55"" endLine=""10"" endColumn=""56"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_2"" parameterNames=""d6""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""125"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""35"" endLine=""11"" endColumn=""36"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""37"" endLine=""11"" endColumn=""47"" document=""1"" /> <entry offset=""0x5"" startLine=""11"" startColumn=""48"" endLine=""11"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalVariables() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; dynamic[] scores = new dynamic[] { ""97"", ""92"", ""81"", ""60"" }; dynamic[] arrDynamic = new dynamic[] { ""1"", ""2"", ""3"" }; while (d1 < 1) { dynamic dInWhile; d1++; } do { dynamic dInDoWhile; d1++; } while (d1 < 1); foreach (int d in arrInt) { dynamic dInForEach; } for (int i = 0; i < 1; i++) { dynamic dInFor; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { dynamic dInIf; } else { dynamic dInElse; } try { dynamic dInTry; throw new Exception(); } catch { dynamic dInCatch; } finally { dynamic dInFinally; } IEnumerable<dynamic> scoreQuery1 = from score in scores select score; dynamic scoreQuery2 = from score in scores select score; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""2"" localName=""scores"" /> <bucket flags=""01"" slotId=""3"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""4"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""5"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""6"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""8"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""13"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""15"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""17"" localName=""d"" /> <bucket flags=""1"" slotId=""20"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""21"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""22"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""23"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""24"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""159"" /> <slot kind=""0"" offset=""1077"" /> <slot kind=""0"" offset=""1169"" /> <slot kind=""0"" offset=""261"" /> <slot kind=""1"" offset=""214"" /> <slot kind=""0"" offset=""345"" /> <slot kind=""1"" offset=""310"" /> <slot kind=""6"" offset=""412"" /> <slot kind=""8"" offset=""412"" /> <slot kind=""0"" offset=""412"" /> <slot kind=""0"" offset=""470"" /> <slot kind=""0"" offset=""511"" /> <slot kind=""0"" offset=""562"" /> <slot kind=""1"" offset=""502"" /> <slot kind=""0"" offset=""603"" /> <slot kind=""1"" offset=""590"" /> <slot kind=""1"" offset=""678"" /> <slot kind=""0"" offset=""723"" /> <slot kind=""0"" offset=""787"" /> <slot kind=""0"" offset=""852"" /> <slot kind=""0"" offset=""954"" /> <slot kind=""0"" offset=""1024"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""1145"" /> <lambda offset=""1237"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""69"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""64"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5e"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x6e"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x72"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x7e"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x84"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x8d"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x95"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x9d"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0xa0"" hidden=""true"" document=""1"" /> <entry offset=""0xa2"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0xa3"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0xa4"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0xaa"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0xb1"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0xbc"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xbf"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0xc0"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0xd0"" hidden=""true"" document=""1"" /> <entry offset=""0xd4"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0xd5"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0xd6"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0xd9"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0xda"" hidden=""true"" document=""1"" /> <entry offset=""0xdb"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0xdc"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0xe2"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0xe3"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0xe4"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xe9"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xea"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xec"" startLine=""56"" startColumn=""9"" endLine=""58"" endColumn=""26"" document=""1"" /> <entry offset=""0x113"" startLine=""59"" startColumn=""9"" endLine=""61"" endColumn=""26"" document=""1"" /> <entry offset=""0x13a"" startLine=""62"" startColumn=""5"" endLine=""62"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13b""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scores"" il_index=""2"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrDynamic"" il_index=""3"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery1"" il_index=""4"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery2"" il_index=""5"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <scope startOffset=""0x5d"" endOffset=""0x63""> <local name=""dInWhile"" il_index=""6"" il_start=""0x5d"" il_end=""0x63"" attributes=""0"" /> </scope> <scope startOffset=""0x6d"" endOffset=""0x73""> <local name=""dInDoWhile"" il_index=""8"" il_start=""0x6d"" il_end=""0x73"" attributes=""0"" /> </scope> <scope startOffset=""0x86"" endOffset=""0x8f""> <local name=""d"" il_index=""12"" il_start=""0x86"" il_end=""0x8f"" attributes=""0"" /> <scope startOffset=""0x8d"" endOffset=""0x8f""> <local name=""dInForEach"" il_index=""13"" il_start=""0x8d"" il_end=""0x8f"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0x9d"" endOffset=""0xb5""> <local name=""i"" il_index=""14"" il_start=""0x9d"" il_end=""0xb5"" attributes=""0"" /> <scope startOffset=""0xa2"" endOffset=""0xa4""> <local name=""dInFor"" il_index=""15"" il_start=""0xa2"" il_end=""0xa4"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0xb5"" endOffset=""0xca""> <local name=""d"" il_index=""17"" il_start=""0xb5"" il_end=""0xca"" attributes=""0"" /> </scope> <scope startOffset=""0xd4"" endOffset=""0xd6""> <local name=""dInIf"" il_index=""20"" il_start=""0xd4"" il_end=""0xd6"" attributes=""0"" /> </scope> <scope startOffset=""0xd8"" endOffset=""0xda""> <local name=""dInElse"" il_index=""21"" il_start=""0xd8"" il_end=""0xda"" attributes=""0"" /> </scope> <scope startOffset=""0xdb"" endOffset=""0xe2""> <local name=""dInTry"" il_index=""22"" il_start=""0xdb"" il_end=""0xe2"" attributes=""0"" /> </scope> <scope startOffset=""0xe3"" endOffset=""0xe5""> <local name=""dInCatch"" il_index=""23"" il_start=""0xe3"" il_end=""0xe5"" attributes=""0"" /> </scope> <scope startOffset=""0xe9"" endOffset=""0xeb""> <local name=""dInFinally"" il_index=""24"" il_start=""0xe9"" il_end=""0xeb"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""58"" startColumn=""20"" endLine=""58"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_1"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""61"" startColumn=""20"" endLine=""61"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalConstants() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; const dynamic scores = null; const dynamic arrDynamic = null; while (d1 < 1) { const dynamic dInWhile = null; d1++; } do { const dynamic dInDoWhile = null; d1++; } while (d1 < 1); foreach (int d in arrInt) { const dynamic dInForEach = null; } for (int i = 0; i < 1; i++) { const dynamic dInFor = null; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { const dynamic dInIf = null; } else { const dynamic dInElse = null; } try { const dynamic dInTry = null; throw new Exception(); } catch { const dynamic dInCatch = null; } finally { const dynamic dInFinally = null; } const IEnumerable<dynamic> scoreQuery1 = null; const dynamic scoreQuery2 = null; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""scores"" /> <bucket flags=""1"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""0"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""0"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""0"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""9"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""0"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""0"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""0"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""268"" /> <slot kind=""6"" offset=""383"" /> <slot kind=""8"" offset=""383"" /> <slot kind=""0"" offset=""383"" /> <slot kind=""0"" offset=""495"" /> <slot kind=""1"" offset=""486"" /> <slot kind=""0"" offset=""600"" /> <slot kind=""1"" offset=""587"" /> <slot kind=""1"" offset=""675"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x2a"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x34"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x43"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x44"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x53"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0x59"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x5a"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0x60"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0x75"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x76"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0x7c"" hidden=""true"" document=""1"" /> <entry offset=""0x80"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0x86"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x8b"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x8c"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0x90"" hidden=""true"" document=""1"" /> <entry offset=""0x91"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0x92"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0x98"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0x99"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x9a"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0x9f"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xa0"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xa2"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa3""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <constant name=""scores"" value=""null"" type=""Object"" /> <constant name=""arrDynamic"" value=""null"" type=""Object"" /> <constant name=""scoreQuery1"" value=""null"" signature=""System.Collections.Generic.IEnumerable`1{Object}"" /> <constant name=""scoreQuery2"" value=""null"" type=""Object"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <constant name=""dInWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x25"" endOffset=""0x2b""> <constant name=""dInDoWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x3c"" endOffset=""0x45""> <local name=""d"" il_index=""6"" il_start=""0x3c"" il_end=""0x45"" attributes=""0"" /> <scope startOffset=""0x43"" endOffset=""0x45""> <constant name=""dInForEach"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x53"" endOffset=""0x6b""> <local name=""i"" il_index=""7"" il_start=""0x53"" il_end=""0x6b"" attributes=""0"" /> <scope startOffset=""0x58"" endOffset=""0x5a""> <constant name=""dInFor"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x6b"" endOffset=""0x80""> <local name=""d"" il_index=""9"" il_start=""0x6b"" il_end=""0x80"" attributes=""0"" /> </scope> <scope startOffset=""0x8a"" endOffset=""0x8c""> <constant name=""dInIf"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x8e"" endOffset=""0x90""> <constant name=""dInElse"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x91"" endOffset=""0x98""> <constant name=""dInTry"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x99"" endOffset=""0x9b""> <constant name=""dInCatch"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x9f"" endOffset=""0xa1""> <constant name=""dInFinally"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { dynamic v1 = 1; const dynamic c1 = null; throw null; dynamic v2 = 1; const dynamic c2 = null; { dynamic v3 = 1; const dynamic c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 10 (0xa) .maxstack 1 .locals init (object V_0, //v1 object V_1, //v2 object V_2) //v3 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldnull IL_0009: throw }"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""v1"" /> <bucket flags=""1"" slotId=""1"" localName=""v2"" /> <bucket flags=""1"" slotId=""0"" localName=""c1"" /> <bucket flags=""1"" slotId=""0"" localName=""c2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""103"" /> <slot kind=""0"" offset=""181"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <constant name=""c1"" value=""null"" type=""Object"" /> <constant name=""c2"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBVarVariableLocal() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic d = ""1""; var v = d; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""1"" localName=""v"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""29"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBGenericDynamicNonLocal() { string source = WithWindowsLineBreaks(@" using System; class dynamic<T> { public T field; } class Test { public static void Main(string[] args) { dynamic<dynamic> obj = new dynamic<dynamic>(); obj.field = ""1""; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""obj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""22"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""49"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""2"" endLine=""13"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x13"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_1() //With 2 normal dynamic locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; dynamic zzz; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""1"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""41"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_2() //With 1 normal dynamic local and 1 containing dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic> zzz; } } class Goo<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""46"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_3() //With 1 normal dynamic local and 1 containing(more than one) dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""68"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_4() //With 1 normal dynamic local, 1 containing dynamic local with a normal local variable { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; int dummy = 0; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""2"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""0"" offset=""92"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""dummy"" il_index=""1"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""zzz"" il_index=""2"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_5_Just_Long() //Dynamic local with dynamic attribute of length 63 above which the flag is emitted empty { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""010101010101010101010101010101010101010101010101010101010101011"" slotId=""0"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""361"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_6_Too_Long() //The limitation of the previous testcase with dynamic attribute length 64 and not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_7() //Corner case dynamic locals with normal locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z1; int dummy1 = 0; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z2; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; int dummy2 = 0; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""389"" /> <slot kind=""0"" offset=""771"" /> <slot kind=""0"" offset=""1145"" /> <slot kind=""0"" offset=""1162"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x6"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z1"" il_index=""0"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy1"" il_index=""1"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z2"" il_index=""2"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z3"" il_index=""3"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy2"" il_index=""4"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_8_Mixed_Corner_Cases() //Mixed case with one more limitation. If identifier length is greater than 63 then the info is not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; dynamic www; dynamic length63length63length63length63length63length63length63length6; dynamic length64length64length64length64length64length64length64length64; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""www"" /> <bucket flags=""1"" slotId=""2"" localName=""length63length63length63length63length63length63length63length6"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""393"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""497"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z3"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length63length63length63length63length63length63length63length6"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length64length64length64length64length64length64length64length64"" il_index=""3"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_9() //Check corner case with only corner cases { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> yes; F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> no; dynamic www; } } class F<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""0000000000000000000000000000000000000000000000000000000000000001"" slotId=""0"" localName=""yes"" /> <bucket flags=""1"" slotId=""2"" localName=""www"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""208"" /> <slot kind=""0"" offset=""422"" /> <slot kind=""0"" offset=""443"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yes"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""no"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_TwoScope() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic simple; for(int x =0 ; x < 10 ; ++x) { dynamic inner; } } static void nothing(dynamic localArg) { dynamic localInner; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""simple"" /> <bucket flags=""1"" slotId=""2"" localName=""inner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""84"" /> <slot kind=""1"" offset=""36"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""24"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x15""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""simple"" il_index=""0"" il_start=""0x0"" il_end=""0x15"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x14""> <local name=""x"" il_index=""1"" il_start=""0x1"" il_end=""0x14"" attributes=""0"" /> <scope startOffset=""0x5"" endOffset=""0x7""> <local name=""inner"" il_index=""2"" il_start=""0x5"" il_end=""0x7"" attributes=""0"" /> </scope> </scope> </scope> </method> <method containingType=""Program"" name=""nothing"" parameterNames=""localArg""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""localInner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""localInner"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(637465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637465")] [Fact] public void DynamicLocalOptimizedAway() { string source = WithWindowsLineBreaks(@" class C { public static void Main() { dynamic d = GetDynamic(); } static dynamic GetDynamic() { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""GetDynamic""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBDynamicLocalsTests : CSharpTestBase { [Fact] public void EmitPDBDynamicObjectVariable1() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { dynamic d1 = new Helper(); dynamic d2 = new Point(); D d4 = new D(d1.goo); Helper d5 = new Helper(d1); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { CSharpRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> <bucket flags=""1"" slotId=""1"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""0"" offset=""98"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""28"" document=""1"" /> <entry offset=""0x17"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""24"" document=""1"" /> <entry offset=""0xb1"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""30"" document=""1"" /> <entry offset=""0x10f"" startLine=""24"" startColumn=""3"" endLine=""24"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x110""> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d2"" il_index=""1"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d4"" il_index=""2"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d5"" il_index=""3"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocals1() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic[] arrDynamic = new dynamic[] {""1""}; foreach (dynamic d in arrDynamic) { //do nothing } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""1"" slotId=""3"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""6"" offset=""58"" /> <slot kind=""8"" offset=""58"" /> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""46"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""31"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""28"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <local name=""arrDynamic"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <local name=""d"" il_index=""3"" il_start=""0x17"" il_end=""0x1d"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicConstVariable() { string source = @" class Test { public static void Main(string[] args) { { const dynamic d = null; const string c = null; } { const dynamic c = null; const dynamic d = null; } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""c"" /> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""d"" value=""null"" type=""Object"" /> <constant name=""c"" value=""null"" type=""String"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""c"" value=""null"" type=""Object"" /> <constant name=""d"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicDuplicateName() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { { dynamic a = null; object b = null; } { dynamic[] a = null; dynamic b = null; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""a"" /> <bucket flags=""01"" slotId=""2"" localName=""a"" /> <bucket flags=""1"" slotId=""3"" localName=""b"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""119"" /> <slot kind=""0"" offset=""150"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""30"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <scope startOffset=""0x1"" endOffset=""0x7""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> </scope> <scope startOffset=""0x7"" endOffset=""0xd""> <local name=""a"" il_index=""2"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> <local name=""b"" il_index=""3"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicVariableNameTooLong() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d12345678901234567890123456789012345678901234567890123456789012"" /> <bucket flags=""1"" slotId=""0"" localName=""b12345678901234567890123456789012345678901234567890123456789012"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""234"" /> <slot kind=""0"" offset=""336"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""89"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""88"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <local name=""c123456789012345678901234567890123456789012345678901234567890123"" il_index=""0"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <local name=""d12345678901234567890123456789012345678901234567890123456789012"" il_index=""1"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <constant name=""a123456789012345678901234567890123456789012345678901234567890123"" value=""null"" type=""Object"" /> <constant name=""b12345678901234567890123456789012345678901234567890123456789012"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicArrayVariable() { string source = WithWindowsLineBreaks(@" class ArrayTest { int x; } class Test { public static void Main(string[] args) { dynamic[] arr = new dynamic[10]; dynamic[,] arrdim = new string[2,3]; dynamic[] arrobj = new ArrayTest[2]; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arr"" /> <bucket flags=""01"" slotId=""1"" localName=""arrdim"" /> <bucket flags=""01"" slotId=""2"" localName=""arrobj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""91"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1e"" startLine=""13"" startColumn=""3"" endLine=""13"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <local name=""arr"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrdim"" il_index=""1"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrobj"" il_index=""2"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicCollectionVariable() { string source = WithWindowsLineBreaks(@" using System.Collections.Generic; class Test { public static void Main(string[] args) { dynamic l1 = new List<int>(); List<dynamic> l2 = new List<dynamic>(); dynamic l3 = new List<dynamic>(); Dictionary<dynamic,dynamic> d1 = new Dictionary<dynamic,dynamic>(); dynamic d2 = new Dictionary<int,int>(); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""l1"" /> <bucket flags=""01"" slotId=""1"" localName=""l2"" /> <bucket flags=""1"" slotId=""2"" localName=""l3"" /> <bucket flags=""011"" slotId=""3"" localName=""d1"" /> <bucket flags=""1"" slotId=""4"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""146"" /> <slot kind=""0"" offset=""197"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""3"" endLine=""6"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""32"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""42"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <namespace name=""System.Collections.Generic"" /> <local name=""l1"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l2"" il_index=""1"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l3"" il_index=""2"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d1"" il_index=""3"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d2"" il_index=""4"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBDynamicObjectVariable2() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { Helper staticObj = new Helper(); dynamic d1 = new Helper(); dynamic d3 = new D(staticObj.goo); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d1"" /> <bucket flags=""1"" slotId=""2"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> <slot kind=""0"" offset=""49"" /> <slot kind=""0"" offset=""79"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""29"" document=""1"" /> <entry offset=""0xd"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""37"" document=""1"" /> <entry offset=""0x1a"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""staticObj"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d1"" il_index=""1"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d3"" il_index=""2"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassConstructorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { public Test() { dynamic d; } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""2"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""d"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassPropertyDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { string field; public dynamic Field { get { dynamic d = field + field; return d; } set { dynamic d = null; //field = d; Not yet implemented in Roslyn } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Field""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Field"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x3"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassOverloadedOperatorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Complex { int real; int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static dynamic operator +(Complex c1, Complex c2) { dynamic d = new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); return d; } } class Test { public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Complex"" name="".ctor"" parameterNames=""real, imaginary""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Complex"" name=""op_Addition"" parameterNames=""c1, c2""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""81"" document=""1"" /> <entry offset=""0x21"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0x25"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassIndexerDynamicLocal() { string source = WithWindowsLineBreaks(@" class Test { dynamic[] arr; public dynamic this[int i] { get { dynamic d = arr[i]; return d; } set { dynamic d = (dynamic) value; arr[i] = d; } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x10"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Item"" parameterNames=""i, value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""41"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0xc"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassEventHandlerDynamicLocal() { string source = WithWindowsLineBreaks(@" using System; class Sample { public static void Main() { ConsoleKeyInfo cki; Console.Clear(); Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); } protected static void myHandler(object sender, ConsoleCancelEventArgs args) { dynamic d; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Sample"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""26"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""76"" document=""1"" /> <entry offset=""0x19"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""cki"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> <method containingType=""Sample"" name=""myHandler"" parameterNames=""sender, args""> <customDebugInfo> <forward declaringType=""Sample"" methodName=""Main"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBStructDynamicLocals() { string source = WithWindowsLineBreaks(@" using System; struct Test { int d; public Test(int d) { dynamic d1; this.d = d; } public int D { get { dynamic d2; return d; } set { dynamic d3; d = value; } } public static Test operator +(Test t1, Test t2) { dynamic d4; return new Test(t1.d + t2.d); } public static void Main() { dynamic d5; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor"" parameterNames=""d""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""get_D""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <local name=""d2"" il_index=""0"" il_start=""0x0"" il_end=""0xc"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_D"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""d3"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""op_Addition"" parameterNames=""t1, t2""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d4"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""38"" document=""1"" /> <entry offset=""0x16"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x18""> <local name=""d4"" il_index=""0"" il_start=""0x0"" il_end=""0x18"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBAnonymousFunctionLocals() { string source = WithWindowsLineBreaks(@" using System; class Test { public delegate dynamic D1(dynamic d1); public delegate void D2(dynamic d2); public static void Main(string[] args) { D1 obj1 = d3 => d3; D2 obj2 = new D2(d4 => { dynamic d5; d5 = d4; }); D1 obj3 = (dynamic d6) => { return d6; }; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""14"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""102"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset=""27"" /> <lambda offset=""63"" /> <lambda offset=""125"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""50"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <namespace name=""System"" /> <local name=""obj1"" il_index=""0"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj2"" il_index=""1"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj3"" il_index=""2"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_0"" parameterNames=""d3""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_1"" parameterNames=""d4""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""73"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""32"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""46"" endLine=""10"" endColumn=""54"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""55"" endLine=""10"" endColumn=""56"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_2"" parameterNames=""d6""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""125"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""35"" endLine=""11"" endColumn=""36"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""37"" endLine=""11"" endColumn=""47"" document=""1"" /> <entry offset=""0x5"" startLine=""11"" startColumn=""48"" endLine=""11"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalVariables() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; dynamic[] scores = new dynamic[] { ""97"", ""92"", ""81"", ""60"" }; dynamic[] arrDynamic = new dynamic[] { ""1"", ""2"", ""3"" }; while (d1 < 1) { dynamic dInWhile; d1++; } do { dynamic dInDoWhile; d1++; } while (d1 < 1); foreach (int d in arrInt) { dynamic dInForEach; } for (int i = 0; i < 1; i++) { dynamic dInFor; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { dynamic dInIf; } else { dynamic dInElse; } try { dynamic dInTry; throw new Exception(); } catch { dynamic dInCatch; } finally { dynamic dInFinally; } IEnumerable<dynamic> scoreQuery1 = from score in scores select score; dynamic scoreQuery2 = from score in scores select score; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""2"" localName=""scores"" /> <bucket flags=""01"" slotId=""3"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""4"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""5"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""6"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""8"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""13"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""15"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""17"" localName=""d"" /> <bucket flags=""1"" slotId=""20"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""21"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""22"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""23"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""24"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""159"" /> <slot kind=""0"" offset=""1077"" /> <slot kind=""0"" offset=""1169"" /> <slot kind=""0"" offset=""261"" /> <slot kind=""1"" offset=""214"" /> <slot kind=""0"" offset=""345"" /> <slot kind=""1"" offset=""310"" /> <slot kind=""6"" offset=""412"" /> <slot kind=""8"" offset=""412"" /> <slot kind=""0"" offset=""412"" /> <slot kind=""0"" offset=""470"" /> <slot kind=""0"" offset=""511"" /> <slot kind=""0"" offset=""562"" /> <slot kind=""1"" offset=""502"" /> <slot kind=""0"" offset=""603"" /> <slot kind=""1"" offset=""590"" /> <slot kind=""1"" offset=""678"" /> <slot kind=""0"" offset=""723"" /> <slot kind=""0"" offset=""787"" /> <slot kind=""0"" offset=""852"" /> <slot kind=""0"" offset=""954"" /> <slot kind=""0"" offset=""1024"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""1145"" /> <lambda offset=""1237"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""69"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""64"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5e"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x6e"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x72"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x7e"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x84"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x8d"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x95"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x9d"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0xa0"" hidden=""true"" document=""1"" /> <entry offset=""0xa2"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0xa3"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0xa4"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0xaa"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0xb1"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0xbc"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xbf"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0xc0"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0xd0"" hidden=""true"" document=""1"" /> <entry offset=""0xd4"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0xd5"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0xd6"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0xd9"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0xda"" hidden=""true"" document=""1"" /> <entry offset=""0xdb"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0xdc"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0xe2"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0xe3"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0xe4"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xe9"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xea"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xec"" startLine=""56"" startColumn=""9"" endLine=""58"" endColumn=""26"" document=""1"" /> <entry offset=""0x113"" startLine=""59"" startColumn=""9"" endLine=""61"" endColumn=""26"" document=""1"" /> <entry offset=""0x13a"" startLine=""62"" startColumn=""5"" endLine=""62"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13b""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scores"" il_index=""2"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrDynamic"" il_index=""3"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery1"" il_index=""4"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery2"" il_index=""5"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <scope startOffset=""0x5d"" endOffset=""0x63""> <local name=""dInWhile"" il_index=""6"" il_start=""0x5d"" il_end=""0x63"" attributes=""0"" /> </scope> <scope startOffset=""0x6d"" endOffset=""0x73""> <local name=""dInDoWhile"" il_index=""8"" il_start=""0x6d"" il_end=""0x73"" attributes=""0"" /> </scope> <scope startOffset=""0x86"" endOffset=""0x8f""> <local name=""d"" il_index=""12"" il_start=""0x86"" il_end=""0x8f"" attributes=""0"" /> <scope startOffset=""0x8d"" endOffset=""0x8f""> <local name=""dInForEach"" il_index=""13"" il_start=""0x8d"" il_end=""0x8f"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0x9d"" endOffset=""0xb5""> <local name=""i"" il_index=""14"" il_start=""0x9d"" il_end=""0xb5"" attributes=""0"" /> <scope startOffset=""0xa2"" endOffset=""0xa4""> <local name=""dInFor"" il_index=""15"" il_start=""0xa2"" il_end=""0xa4"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0xb5"" endOffset=""0xca""> <local name=""d"" il_index=""17"" il_start=""0xb5"" il_end=""0xca"" attributes=""0"" /> </scope> <scope startOffset=""0xd4"" endOffset=""0xd6""> <local name=""dInIf"" il_index=""20"" il_start=""0xd4"" il_end=""0xd6"" attributes=""0"" /> </scope> <scope startOffset=""0xd8"" endOffset=""0xda""> <local name=""dInElse"" il_index=""21"" il_start=""0xd8"" il_end=""0xda"" attributes=""0"" /> </scope> <scope startOffset=""0xdb"" endOffset=""0xe2""> <local name=""dInTry"" il_index=""22"" il_start=""0xdb"" il_end=""0xe2"" attributes=""0"" /> </scope> <scope startOffset=""0xe3"" endOffset=""0xe5""> <local name=""dInCatch"" il_index=""23"" il_start=""0xe3"" il_end=""0xe5"" attributes=""0"" /> </scope> <scope startOffset=""0xe9"" endOffset=""0xeb""> <local name=""dInFinally"" il_index=""24"" il_start=""0xe9"" il_end=""0xeb"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""58"" startColumn=""20"" endLine=""58"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_1"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""61"" startColumn=""20"" endLine=""61"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalConstants() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; const dynamic scores = null; const dynamic arrDynamic = null; while (d1 < 1) { const dynamic dInWhile = null; d1++; } do { const dynamic dInDoWhile = null; d1++; } while (d1 < 1); foreach (int d in arrInt) { const dynamic dInForEach = null; } for (int i = 0; i < 1; i++) { const dynamic dInFor = null; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { const dynamic dInIf = null; } else { const dynamic dInElse = null; } try { const dynamic dInTry = null; throw new Exception(); } catch { const dynamic dInCatch = null; } finally { const dynamic dInFinally = null; } const IEnumerable<dynamic> scoreQuery1 = null; const dynamic scoreQuery2 = null; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""scores"" /> <bucket flags=""1"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""0"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""0"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""0"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""9"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""0"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""0"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""0"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""268"" /> <slot kind=""6"" offset=""383"" /> <slot kind=""8"" offset=""383"" /> <slot kind=""0"" offset=""383"" /> <slot kind=""0"" offset=""495"" /> <slot kind=""1"" offset=""486"" /> <slot kind=""0"" offset=""600"" /> <slot kind=""1"" offset=""587"" /> <slot kind=""1"" offset=""675"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x2a"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x34"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x43"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x44"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x53"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0x59"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x5a"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0x60"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0x75"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x76"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0x7c"" hidden=""true"" document=""1"" /> <entry offset=""0x80"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0x86"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x8b"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x8c"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0x90"" hidden=""true"" document=""1"" /> <entry offset=""0x91"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0x92"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0x98"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0x99"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x9a"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0x9f"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xa0"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xa2"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa3""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <constant name=""scores"" value=""null"" type=""Object"" /> <constant name=""arrDynamic"" value=""null"" type=""Object"" /> <constant name=""scoreQuery1"" value=""null"" signature=""System.Collections.Generic.IEnumerable`1{Object}"" /> <constant name=""scoreQuery2"" value=""null"" type=""Object"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <constant name=""dInWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x25"" endOffset=""0x2b""> <constant name=""dInDoWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x3c"" endOffset=""0x45""> <local name=""d"" il_index=""6"" il_start=""0x3c"" il_end=""0x45"" attributes=""0"" /> <scope startOffset=""0x43"" endOffset=""0x45""> <constant name=""dInForEach"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x53"" endOffset=""0x6b""> <local name=""i"" il_index=""7"" il_start=""0x53"" il_end=""0x6b"" attributes=""0"" /> <scope startOffset=""0x58"" endOffset=""0x5a""> <constant name=""dInFor"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x6b"" endOffset=""0x80""> <local name=""d"" il_index=""9"" il_start=""0x6b"" il_end=""0x80"" attributes=""0"" /> </scope> <scope startOffset=""0x8a"" endOffset=""0x8c""> <constant name=""dInIf"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x8e"" endOffset=""0x90""> <constant name=""dInElse"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x91"" endOffset=""0x98""> <constant name=""dInTry"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x99"" endOffset=""0x9b""> <constant name=""dInCatch"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x9f"" endOffset=""0xa1""> <constant name=""dInFinally"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { dynamic v1 = 1; const dynamic c1 = null; throw null; dynamic v2 = 1; const dynamic c2 = null; { dynamic v3 = 1; const dynamic c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 10 (0xa) .maxstack 1 .locals init (object V_0, //v1 object V_1, //v2 object V_2) //v3 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldnull IL_0009: throw }"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""v1"" /> <bucket flags=""1"" slotId=""1"" localName=""v2"" /> <bucket flags=""1"" slotId=""0"" localName=""c1"" /> <bucket flags=""1"" slotId=""0"" localName=""c2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""103"" /> <slot kind=""0"" offset=""181"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <constant name=""c1"" value=""null"" type=""Object"" /> <constant name=""c2"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBVarVariableLocal() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic d = ""1""; var v = d; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""1"" localName=""v"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""29"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBGenericDynamicNonLocal() { string source = WithWindowsLineBreaks(@" using System; class dynamic<T> { public T field; } class Test { public static void Main(string[] args) { dynamic<dynamic> obj = new dynamic<dynamic>(); obj.field = ""1""; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""obj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""22"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""49"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""2"" endLine=""13"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x13"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_1() //With 2 normal dynamic locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; dynamic zzz; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""1"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""41"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_2() //With 1 normal dynamic local and 1 containing dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic> zzz; } } class Goo<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""46"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_3() //With 1 normal dynamic local and 1 containing(more than one) dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""68"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_4() //With 1 normal dynamic local, 1 containing dynamic local with a normal local variable { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; int dummy = 0; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""2"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""0"" offset=""92"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""dummy"" il_index=""1"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""zzz"" il_index=""2"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_5_Just_Long() //Dynamic local with dynamic attribute of length 63 above which the flag is emitted empty { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""010101010101010101010101010101010101010101010101010101010101011"" slotId=""0"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""361"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_6_Too_Long() //The limitation of the previous testcase with dynamic attribute length 64 and not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_7() //Corner case dynamic locals with normal locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z1; int dummy1 = 0; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z2; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; int dummy2 = 0; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""389"" /> <slot kind=""0"" offset=""771"" /> <slot kind=""0"" offset=""1145"" /> <slot kind=""0"" offset=""1162"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x6"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z1"" il_index=""0"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy1"" il_index=""1"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z2"" il_index=""2"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z3"" il_index=""3"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy2"" il_index=""4"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_8_Mixed_Corner_Cases() //Mixed case with one more limitation. If identifier length is greater than 63 then the info is not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; dynamic www; dynamic length63length63length63length63length63length63length63length6; dynamic length64length64length64length64length64length64length64length64; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""www"" /> <bucket flags=""1"" slotId=""2"" localName=""length63length63length63length63length63length63length63length6"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""393"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""497"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z3"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length63length63length63length63length63length63length63length6"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length64length64length64length64length64length64length64length64"" il_index=""3"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_9() //Check corner case with only corner cases { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> yes; F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> no; dynamic www; } } class F<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""0000000000000000000000000000000000000000000000000000000000000001"" slotId=""0"" localName=""yes"" /> <bucket flags=""1"" slotId=""2"" localName=""www"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""208"" /> <slot kind=""0"" offset=""422"" /> <slot kind=""0"" offset=""443"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yes"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""no"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_TwoScope() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic simple; for(int x =0 ; x < 10 ; ++x) { dynamic inner; } } static void nothing(dynamic localArg) { dynamic localInner; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""simple"" /> <bucket flags=""1"" slotId=""2"" localName=""inner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""84"" /> <slot kind=""1"" offset=""36"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""24"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x15""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""simple"" il_index=""0"" il_start=""0x0"" il_end=""0x15"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x14""> <local name=""x"" il_index=""1"" il_start=""0x1"" il_end=""0x14"" attributes=""0"" /> <scope startOffset=""0x5"" endOffset=""0x7""> <local name=""inner"" il_index=""2"" il_start=""0x5"" il_end=""0x7"" attributes=""0"" /> </scope> </scope> </scope> </method> <method containingType=""Program"" name=""nothing"" parameterNames=""localArg""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""localInner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""localInner"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(637465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637465")] [Fact] public void DynamicLocalOptimizedAway() { string source = WithWindowsLineBreaks(@" class C { public static void Main() { dynamic d = GetDynamic(); } static dynamic GetDynamic() { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""GetDynamic""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/InternalUtilities/EnumField.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal readonly struct EnumField { public static readonly IComparer<EnumField> Comparer = new EnumFieldComparer(); public readonly string Name; public readonly ulong Value; public readonly object? IdentityOpt; public EnumField(string name, ulong value, object? identityOpt = null) { RoslynDebug.Assert(name != null); this.Name = name; this.Value = value; this.IdentityOpt = identityOpt; } public bool IsDefault { get { return this.Name == null; } } private string GetDebuggerDisplay() { return string.Format("{{{0} = {1}}}", this.Name, this.Value); } internal static EnumField FindValue(ArrayBuilder<EnumField> sortedFields, ulong value) { int start = 0; int end = sortedFields.Count; while (start < end) { int mid = start + (end - start) / 2; long diff = unchecked((long)value - (long)sortedFields[mid].Value); // NOTE: Has to match the comparer below. if (diff == 0) { while (mid >= start && sortedFields[mid].Value == value) { mid--; } return sortedFields[mid + 1]; } else if (diff > 0) { end = mid; // Exclude mid. } else { start = mid + 1; // Exclude mid. } } return default(EnumField); } private class EnumFieldComparer : IComparer<EnumField> { int IComparer<EnumField>.Compare(EnumField field1, EnumField field2) { // Sort order is descending value, then ascending name. int diff = unchecked(((long)field2.Value).CompareTo((long)field1.Value)); return diff == 0 ? string.CompareOrdinal(field1.Name, field2.Name) : diff; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal readonly struct EnumField { public static readonly IComparer<EnumField> Comparer = new EnumFieldComparer(); public readonly string Name; public readonly ulong Value; public readonly object? IdentityOpt; public EnumField(string name, ulong value, object? identityOpt = null) { RoslynDebug.Assert(name != null); this.Name = name; this.Value = value; this.IdentityOpt = identityOpt; } public bool IsDefault { get { return this.Name == null; } } private string GetDebuggerDisplay() { return string.Format("{{{0} = {1}}}", this.Name, this.Value); } internal static EnumField FindValue(ArrayBuilder<EnumField> sortedFields, ulong value) { int start = 0; int end = sortedFields.Count; while (start < end) { int mid = start + (end - start) / 2; long diff = unchecked((long)value - (long)sortedFields[mid].Value); // NOTE: Has to match the comparer below. if (diff == 0) { while (mid >= start && sortedFields[mid].Value == value) { mid--; } return sortedFields[mid + 1]; } else if (diff > 0) { end = mid; // Exclude mid. } else { start = mid + 1; // Exclude mid. } } return default(EnumField); } private class EnumFieldComparer : IComparer<EnumField> { int IComparer<EnumField>.Compare(EnumField field1, EnumField field2) { // Sort order is descending value, then ascending name. int diff = unchecked(((long)field2.Value).CompareTo((long)field1.Value)); return diff == 0 ? string.CompareOrdinal(field1.Name, field2.Name) : diff; } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/FindUsages/FindUsagesContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal abstract class FindUsagesContext : IFindUsagesContext { public IStreamingProgressTracker ProgressTracker { get; } protected FindUsagesContext() => this.ProgressTracker = new StreamingProgressTracker(this.ReportProgressAsync); public virtual ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => default; public virtual ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => default; public virtual ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default; public virtual ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) => default; public virtual ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => default; protected virtual ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) => 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. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal abstract class FindUsagesContext : IFindUsagesContext { public IStreamingProgressTracker ProgressTracker { get; } protected FindUsagesContext() => this.ProgressTracker = new StreamingProgressTracker(this.ReportProgressAsync); public virtual ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => default; public virtual ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => default; public virtual ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default; public virtual ValueTask OnDefinitionFoundAsync(DefinitionItem definition, CancellationToken cancellationToken) => default; public virtual ValueTask OnReferenceFoundAsync(SourceReferenceItem reference, CancellationToken cancellationToken) => default; protected virtual ValueTask ReportProgressAsync(int current, int maximum, CancellationToken cancellationToken) => default; } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/RenameShortcutKeys.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class RenameShortcutKey { public static string RenameOverloads { get; } public static string SearchInStrings { get; } public static string SearchInComments { get; } public static string PreviewChanges { get; } public static string Apply { get; } public static string RenameFile { get; } static RenameShortcutKey() { RenameOverloads = ExtractAccessKey(EditorFeaturesResources.Include_overload_s, "O"); SearchInStrings = ExtractAccessKey(EditorFeaturesResources.Include_strings, "S"); SearchInComments = ExtractAccessKey(EditorFeaturesResources.Include_comments, "C"); PreviewChanges = ExtractAccessKey(EditorFeaturesResources.Preview_changes1, "P"); Apply = ExtractAccessKey(EditorFeaturesResources.Apply1, "A"); RenameFile = ExtractAccessKey(EditorFeaturesResources.Rename_symbols_file, "F"); } /// <summary> /// Given a localized label, searches for _ and extracts the accelerator key. If none found, /// returns defaultValue. /// </summary> private static string ExtractAccessKey(string localizedLabel, string defaultValue) { var underscoreIndex = localizedLabel.IndexOf('_'); if (underscoreIndex >= 0 && underscoreIndex < localizedLabel.Length - 1) { return new string(new char[] { char.ToUpperInvariant(localizedLabel[underscoreIndex + 1]) }); } Debug.Fail("Could not locate accelerator for " + localizedLabel + " for the rename dashboard"); return defaultValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal class RenameShortcutKey { public static string RenameOverloads { get; } public static string SearchInStrings { get; } public static string SearchInComments { get; } public static string PreviewChanges { get; } public static string Apply { get; } public static string RenameFile { get; } static RenameShortcutKey() { RenameOverloads = ExtractAccessKey(EditorFeaturesResources.Include_overload_s, "O"); SearchInStrings = ExtractAccessKey(EditorFeaturesResources.Include_strings, "S"); SearchInComments = ExtractAccessKey(EditorFeaturesResources.Include_comments, "C"); PreviewChanges = ExtractAccessKey(EditorFeaturesResources.Preview_changes1, "P"); Apply = ExtractAccessKey(EditorFeaturesResources.Apply1, "A"); RenameFile = ExtractAccessKey(EditorFeaturesResources.Rename_symbols_file, "F"); } /// <summary> /// Given a localized label, searches for _ and extracts the accelerator key. If none found, /// returns defaultValue. /// </summary> private static string ExtractAccessKey(string localizedLabel, string defaultValue) { var underscoreIndex = localizedLabel.IndexOf('_'); if (underscoreIndex >= 0 && underscoreIndex < localizedLabel.Length - 1) { return new string(new char[] { char.ToUpperInvariant(localizedLabel[underscoreIndex + 1]) }); } Debug.Fail("Could not locate accelerator for " + localizedLabel + " for the rename dashboard"); return defaultValue; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Cocoa/Preview/PreviewFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : AbstractPreviewFactoryService<ICocoaDifferenceViewer>, IPreviewFactoryService { private readonly ICocoaDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewFactoryService( IThreadingContext threadingContext, ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ICocoaTextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, ICocoaDifferenceViewerFactoryService differenceViewerService) : base(threadingContext, textBufferFactoryService, contentTypeRegistryService, projectionBufferFactoryService, editorOptionsFactoryService, differenceSelectorService, differenceBufferService, textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable)) { _differenceViewerService = differenceViewerService; } protected override async Task<ICocoaDifferenceViewer> CreateDifferenceViewAsync(IDifferenceBuffer diffBuffer, ITextViewRoleSet previewRoleSet, DifferenceViewMode mode, double zoomLevel, CancellationToken cancellationToken) { var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, previewRoleSet); diffViewer.ViewMode = mode; // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync(ThreadingContext, cancellationToken: cancellationToken).ConfigureAwait(true); return diffViewer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : AbstractPreviewFactoryService<ICocoaDifferenceViewer>, IPreviewFactoryService { private readonly ICocoaDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewFactoryService( IThreadingContext threadingContext, ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ICocoaTextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, ICocoaDifferenceViewerFactoryService differenceViewerService) : base(threadingContext, textBufferFactoryService, contentTypeRegistryService, projectionBufferFactoryService, editorOptionsFactoryService, differenceSelectorService, differenceBufferService, textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable)) { _differenceViewerService = differenceViewerService; } protected override async Task<ICocoaDifferenceViewer> CreateDifferenceViewAsync(IDifferenceBuffer diffBuffer, ITextViewRoleSet previewRoleSet, DifferenceViewMode mode, double zoomLevel, CancellationToken cancellationToken) { var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, previewRoleSet); diffViewer.ViewMode = mode; // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync(ThreadingContext, cancellationToken: cancellationToken).ConfigureAwait(true); return diffViewer; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/HeaderMenuItemViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// The view model used for the header of TargetMenuItemViewModel. /// e.g. /// 'I↓ Implementing members' /// Method 'Bar' /// </summary> internal class HeaderMenuItemViewModel : InheritanceMenuItemViewModel { public HeaderMenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) : base(displayContent, imageMoniker, automationName) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// The view model used for the header of TargetMenuItemViewModel. /// e.g. /// 'I↓ Implementing members' /// Method 'Bar' /// </summary> internal class HeaderMenuItemViewModel : InheritanceMenuItemViewModel { public HeaderMenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) : base(displayContent, imageMoniker, automationName) { } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TreeData.NodeAndText.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class TreeData { private class NodeAndText : TreeData { private readonly SourceText _text; public NodeAndText(SyntaxNode root, SourceText text) : base(root) { Contract.ThrowIfNull(text); _text = text; } public override int GetOriginalColumn(int tabSize, SyntaxToken token) { Contract.ThrowIfTrue(token.RawKind == 0); var line = _text.Lines.GetLineFromPosition(token.SpanStart); return line.GetColumnFromLineOffset(token.SpanStart - line.Start, tabSize); } public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { if (token1.RawKind == 0) { // get leading trivia text return _text.ToString(TextSpan.FromBounds(token2.FullSpan.Start, token2.SpanStart)); } if (token2.RawKind == 0) { // get trailing trivia text return _text.ToString(TextSpan.FromBounds(token1.Span.End, token1.FullSpan.End)); } return _text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { internal abstract partial class TreeData { private class NodeAndText : TreeData { private readonly SourceText _text; public NodeAndText(SyntaxNode root, SourceText text) : base(root) { Contract.ThrowIfNull(text); _text = text; } public override int GetOriginalColumn(int tabSize, SyntaxToken token) { Contract.ThrowIfTrue(token.RawKind == 0); var line = _text.Lines.GetLineFromPosition(token.SpanStart); return line.GetColumnFromLineOffset(token.SpanStart - line.Start, tabSize); } public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { if (token1.RawKind == 0) { // get leading trivia text return _text.ToString(TextSpan.FromBounds(token2.FullSpan.Start, token2.SpanStart)); } if (token2.RawKind == 0) { // get trailing trivia text return _text.ToString(TextSpan.FromBounds(token1.Span.End, token1.FullSpan.End)); } return _text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/InternalUtilities/ImmutableSetWithInsertionOrder`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.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Roslyn.Utilities { internal sealed class ImmutableSetWithInsertionOrder<T> : IEnumerable<T> where T : notnull { public static readonly ImmutableSetWithInsertionOrder<T> Empty = new ImmutableSetWithInsertionOrder<T>(ImmutableDictionary.Create<T, uint>(), 0u); private readonly ImmutableDictionary<T, uint> _map; private readonly uint _nextElementValue; private ImmutableSetWithInsertionOrder(ImmutableDictionary<T, uint> map, uint nextElementValue) { _map = map; _nextElementValue = nextElementValue; } public int Count { get { return _map.Count; } } public bool Contains(T value) { return _map.ContainsKey(value); } public ImmutableSetWithInsertionOrder<T> Add(T value) { // no reason to cause allocations if value is already in the set if (_map.ContainsKey(value)) { return this; } return new ImmutableSetWithInsertionOrder<T>(_map.Add(value, _nextElementValue), _nextElementValue + 1u); } public ImmutableSetWithInsertionOrder<T> Remove(T value) { var modifiedMap = _map.Remove(value); if (modifiedMap == _map) { // no reason to cause allocations if value is missing return this; } return this.Count == 1 ? Empty : new ImmutableSetWithInsertionOrder<T>(modifiedMap, _nextElementValue); } public IEnumerable<T> InInsertionOrder { get { return _map.OrderBy(kv => kv.Value).Select(kv => kv.Key); } } public override string ToString() { return "{" + string.Join(", ", this) + "}"; } public IEnumerator<T> GetEnumerator() { return _map.Keys.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _map.Keys.GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Roslyn.Utilities { internal sealed class ImmutableSetWithInsertionOrder<T> : IEnumerable<T> where T : notnull { public static readonly ImmutableSetWithInsertionOrder<T> Empty = new ImmutableSetWithInsertionOrder<T>(ImmutableDictionary.Create<T, uint>(), 0u); private readonly ImmutableDictionary<T, uint> _map; private readonly uint _nextElementValue; private ImmutableSetWithInsertionOrder(ImmutableDictionary<T, uint> map, uint nextElementValue) { _map = map; _nextElementValue = nextElementValue; } public int Count { get { return _map.Count; } } public bool Contains(T value) { return _map.ContainsKey(value); } public ImmutableSetWithInsertionOrder<T> Add(T value) { // no reason to cause allocations if value is already in the set if (_map.ContainsKey(value)) { return this; } return new ImmutableSetWithInsertionOrder<T>(_map.Add(value, _nextElementValue), _nextElementValue + 1u); } public ImmutableSetWithInsertionOrder<T> Remove(T value) { var modifiedMap = _map.Remove(value); if (modifiedMap == _map) { // no reason to cause allocations if value is missing return this; } return this.Count == 1 ? Empty : new ImmutableSetWithInsertionOrder<T>(modifiedMap, _nextElementValue); } public IEnumerable<T> InInsertionOrder { get { return _map.OrderBy(kv => kv.Value).Select(kv => kv.Key); } } public override string ToString() { return "{" + string.Join(", ", this) + "}"; } public IEnumerator<T> GetEnumerator() { return _map.Keys.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _map.Keys.GetEnumerator(); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/PEWriter/ManagedResource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class ManagedResource { private readonly Func<Stream>? _streamProvider; private readonly IFileReference? _fileReference; private readonly uint _offset; private readonly string _name; private readonly bool _isPublic; /// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func<Stream>? streamProvider, IFileReference? fileReference, uint offset) { RoslynDebug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; } public void WriteData(BlobBuilder resourceWriter) { if (_fileReference == null) { try { #nullable disable // Can '_streamProvider' be null? https://github.com/dotnet/roslyn/issues/39166 using (Stream stream = _streamProvider()) #nullable enable { if (stream == null) { throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); } var count = (int)(stream.Length - stream.Position); resourceWriter.WriteInt32(count); int bytesWritten = resourceWriter.TryWriteBytes(stream, count); if (bytesWritten != count) { throw new EndOfStreamException( string.Format(CultureInfo.CurrentUICulture, CodeAnalysisResources.ResourceStreamEndedUnexpectedly, bytesWritten, count)); } resourceWriter.Align(8); } } catch (Exception e) { throw new ResourceException(_name, e); } } } public IFileReference? ExternalFile { get { return _fileReference; } } public uint Offset { get { return _offset; } } public IEnumerable<ICustomAttribute> Attributes { get { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } } public bool IsPublic { get { return _isPublic; } } public string Name { get { return _name; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class ManagedResource { private readonly Func<Stream>? _streamProvider; private readonly IFileReference? _fileReference; private readonly uint _offset; private readonly string _name; private readonly bool _isPublic; /// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func<Stream>? streamProvider, IFileReference? fileReference, uint offset) { RoslynDebug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; } public void WriteData(BlobBuilder resourceWriter) { if (_fileReference == null) { try { #nullable disable // Can '_streamProvider' be null? https://github.com/dotnet/roslyn/issues/39166 using (Stream stream = _streamProvider()) #nullable enable { if (stream == null) { throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); } var count = (int)(stream.Length - stream.Position); resourceWriter.WriteInt32(count); int bytesWritten = resourceWriter.TryWriteBytes(stream, count); if (bytesWritten != count) { throw new EndOfStreamException( string.Format(CultureInfo.CurrentUICulture, CodeAnalysisResources.ResourceStreamEndedUnexpectedly, bytesWritten, count)); } resourceWriter.Align(8); } } catch (Exception e) { throw new ResourceException(_name, e); } } } public IFileReference? ExternalFile { get { return _fileReference; } } public uint Offset { get { return _offset; } } public IEnumerable<ICustomAttribute> Attributes { get { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } } public bool IsPublic { get { return _isPublic; } } public string Name { get { return _name; } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var checksum = checksums.Text; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document), textSpan, checksum, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var checksum = checksums.Text; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document), textSpan, checksum, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/WellKnownMembers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class WellKnownMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static WellKnownMembers() { byte[] initializationBytes = new byte[] { // System_Math__RoundDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__PowDoubleDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Array__get_Length (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Array__Empty (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Convert__ToBooleanDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToBooleanInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Convert__ToBooleanUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Convert__ToBooleanInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Convert__ToBooleanUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Convert__ToBooleanSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToBooleanDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToSByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToSingleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToDoubleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_CLSCompliantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_CLSCompliantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_FlagsAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_FlagsAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Guid__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Guid, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Type__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Type__GetTypeFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Type__Missing (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Field Signature // System_Type__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Reflection_AssemblyKeyFileAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyFileAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_AssemblyKeyNameAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyNameAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_MethodBase__GetMethodFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, // System_Reflection_MethodBase__GetMethodFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_MethodInfo__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Reflection_MethodInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Delegate__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, // System_Delegate__CreateDelegate4 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Reflection_FieldInfo__GetFieldFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Reflection_FieldInfo__GetFieldFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_Missing__Value (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_Missing, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_Missing, // Field Signature // System_IEquatable_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_IEquatable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IEqualityComparer_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__get_Default (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T,// Return Type // System_AttributeUsageAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, 0, // System_AttributeUsageAttribute__AllowMultiple (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_AttributeUsageAttribute__Inherited (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_ParamArrayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ParamArrayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_STAThreadAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_STAThreadAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Reflection_DefaultMemberAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_DefaultMemberAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_Debugger__Break (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_Debugger, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerDisplayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_DebuggerDisplayAttribute__Type (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerHiddenAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableState, // System_Diagnostics_DebuggerStepThroughAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Runtime_InteropServices_UnknownWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnknownWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_DispatchWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispatchWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, // System_Runtime_InteropServices_CoClassAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_CoClassAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComAwareEventInfo__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComVisibleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DispIdAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispIdAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_GuidAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_GuidAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ComInterfaceType, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_Marshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_BestFitMappingAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_LCIDConversionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_CallingConvention, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Func_T2, 2, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ExtensionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_FixedBufferAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_DynamicAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_CallSite_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, // System_Runtime_CompilerServices_CallSite_T__Target (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices__GetSubArray_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_UnverifiableCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_UnverifiableCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_Permissions_SecurityAction__RequestMinimum (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Security_Permissions_SecurityAction, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // Field Signature // System_Security_Permissions_SecurityPermissionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Activator__CreateInstance (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Activator__CreateInstance_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Threading_Interlocked__CompareExchange (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Interlocked__CompareExchange_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Threading_Monitor__Enter (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Monitor__Enter2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Threading_Monitor__Exit (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Thread__CurrentThread (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Thread, // Return Type // System_Threading_Thread__ManagedThreadId (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Convert (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__GetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Invoke (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__SetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State (byte)MemberFlags.Field, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Field Signature // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Embedded__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_Embedded, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Interaction__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Interaction, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_Strings__AscCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__AscWCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscWStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__ChrInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_Strings__ChrWInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Xml_Linq_XElement__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XElement__ctor2 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XNamespace__Get (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Xml_Linq_XNamespace, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XNamespace, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Windows_Forms_Application__RunForm (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Windows_Forms_Application, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Windows_Forms_Form, // System_Environment__CurrentManagedThreadId (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Environment, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ComponentModel_EditorBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ComponentModel_EditorBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_ComponentModel_EditorBrowsableState, // System_Runtime_GCLatencyMode__SustainedLowLatency (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_GCLatencyMode, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_GCLatencyMode, // Field Signature // System_ValueTuple_T1__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T3__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T4__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T4__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T5__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T5__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T5__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T6__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T6__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T6__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T6__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T7__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T7__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T7__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T7__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T7__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_TRest__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_TRest__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_TRest__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_TRest__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_TRest__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_TRest__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Rest (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 7, // Field Signature // System_ValueTuple_T1__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_ValueTuple_T2__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, // System_ValueTuple_T3__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, // System_ValueTuple_T4__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, // System_ValueTuple_T_T2_T3_T4_T5__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, // System_ValueTuple_T6__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, // System_ValueTuple_T7__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, // System_ValueTuple_TRest__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, (byte)SignatureTypeCode.GenericTypeParameter, 7, // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_TupleElementNamesAttribute // DeclaringTypeId - WellKnownType.ExtSentinel), 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Format_IFormatProvider (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_IFormatProvider, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_NullableAttribute__ctorByte (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableContextAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ReferenceAssemblyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_ObsoleteAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ObsoleteAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Span__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ReadOnlySpan__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Conversion__FixSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__FixDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // Microsoft_VisualBasic_Conversion__IntSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__IntDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // System_Math__CeilingDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__FloorDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__TruncateDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Index__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Index__GetOffset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Range__ctor (byte)(MemberFlags.Constructor), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__StartAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__EndAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_All (byte)(MemberFlags.PropertyGet | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Range__get_Start (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_End (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_IAsyncDisposable__DisposeAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_IAsyncDisposable - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // Return Type: ValueTask // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: IAsyncEnumerator<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, // Argument: CancellationToken (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: ValueTask<bool> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_Generic_IAsyncEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_IValueTaskSource__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_ValueTask_T__ctorSourceAndToken (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: IValueTaskSource<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Threading_Tasks_ValueTask_T__ctorValue (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_ValueTask__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // Argument: IValueTaskSource (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_ITuple__get_Item (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ITuple__get_Length (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_InvalidOperationException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_InvalidOperationException - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_CancellationToken__Equals (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__CreateLinkedTokenSource (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__Token (byte)MemberFlags.Property, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Return Type // System_Threading_CancellationTokenSource__Dispose (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Text_StringBuilder__AppendString (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Text_StringBuilder__AppendChar (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Text_StringBuilder__AppendObject (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Text_StringBuilder__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type }; string[] allNames = new string[(int)WellKnownMember.Count] { "Round", // System_Math__RoundDouble "Pow", // System_Math__PowDoubleDouble "get_Length", // System_Array__get_Length "Empty", // System_Array__Empty "ToBoolean", // System_Convert__ToBooleanDecimal "ToBoolean", // System_Convert__ToBooleanInt32 "ToBoolean", // System_Convert__ToBooleanUInt32 "ToBoolean", // System_Convert__ToBooleanInt64 "ToBoolean", // System_Convert__ToBooleanUInt64 "ToBoolean", // System_Convert__ToBooleanSingle "ToBoolean", // System_Convert__ToBooleanDouble "ToSByte", // System_Convert__ToSByteDecimal "ToSByte", // System_Convert__ToSByteDouble "ToSByte", // System_Convert__ToSByteSingle "ToByte", // System_Convert__ToByteDecimal "ToByte", // System_Convert__ToByteDouble "ToByte", // System_Convert__ToByteSingle "ToInt16", // System_Convert__ToInt16Decimal "ToInt16", // System_Convert__ToInt16Double "ToInt16", // System_Convert__ToInt16Single "ToUInt16", // System_Convert__ToUInt16Decimal "ToUInt16", // System_Convert__ToUInt16Double "ToUInt16", // System_Convert__ToUInt16Single "ToInt32", // System_Convert__ToInt32Decimal "ToInt32", // System_Convert__ToInt32Double "ToInt32", // System_Convert__ToInt32Single "ToUInt32", // System_Convert__ToUInt32Decimal "ToUInt32", // System_Convert__ToUInt32Double "ToUInt32", // System_Convert__ToUInt32Single "ToInt64", // System_Convert__ToInt64Decimal "ToInt64", // System_Convert__ToInt64Double "ToInt64", // System_Convert__ToInt64Single "ToUInt64", // System_Convert__ToUInt64Decimal "ToUInt64", // System_Convert__ToUInt64Double "ToUInt64", // System_Convert__ToUInt64Single "ToSingle", // System_Convert__ToSingleDecimal "ToDouble", // System_Convert__ToDoubleDecimal ".ctor", // System_CLSCompliantAttribute__ctor ".ctor", // System_FlagsAttribute__ctor ".ctor", // System_Guid__ctor "GetTypeFromCLSID", // System_Type__GetTypeFromCLSID "GetTypeFromHandle", // System_Type__GetTypeFromHandle "Missing", // System_Type__Missing WellKnownMemberNames.EqualityOperatorName, // System_Type__op_Equality ".ctor", // System_Reflection_AssemblyKeyFileAttribute__ctor ".ctor", // System_Reflection_AssemblyKeyNameAttribute__ctor "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle2 "CreateDelegate", // System_Reflection_MethodInfo__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate4 "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle2 "Value", // System_Reflection_Missing__Value "Equals", // System_IEquatable_T__Equals "Equals", // System_Collections_Generic_IEqualityComparer_T__Equals "Equals", // System_Collections_Generic_EqualityComparer_T__Equals "GetHashCode", // System_Collections_Generic_EqualityComparer_T__GetHashCode "get_Default", // System_Collections_Generic_EqualityComparer_T__get_Default ".ctor", // System_AttributeUsageAttribute__ctor "AllowMultiple", // System_AttributeUsageAttribute__AllowMultiple "Inherited", // System_AttributeUsageAttribute__Inherited ".ctor", // System_ParamArrayAttribute__ctor ".ctor", // System_STAThreadAttribute__ctor ".ctor", // System_Reflection_DefaultMemberAttribute__ctor "Break", // System_Diagnostics_Debugger__Break ".ctor", // System_Diagnostics_DebuggerDisplayAttribute__ctor "Type", // System_Diagnostics_DebuggerDisplayAttribute__Type ".ctor", // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor ".ctor", // System_Diagnostics_DebuggerHiddenAttribute__ctor ".ctor", // System_Diagnostics_DebuggerBrowsableAttribute__ctor ".ctor", // System_Diagnostics_DebuggerStepThroughAttribute__ctor ".ctor", // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes "Default", // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default "DisableOptimizations", // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations "EnableEditAndContinue", // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue "IgnoreSymbolStoreSequencePoints", // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints ".ctor", // System_Runtime_InteropServices_UnknownWrapper__ctor ".ctor", // System_Runtime_InteropServices_DispatchWrapper__ctor ".ctor", // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType ".ctor", // System_Runtime_InteropServices_CoClassAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComAwareEventInfo__ctor "AddEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler "RemoveEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler ".ctor", // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString ".ctor", // System_Runtime_InteropServices_ComVisibleAttribute__ctor ".ctor", // System_Runtime_InteropServices_DispIdAttribute__ctor ".ctor", // System_Runtime_InteropServices_GuidAttribute__ctor ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 "GetTypeFromCLSID", // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString ".ctor", // System_Runtime_InteropServices_BestFitMappingAttribute__ctor ".ctor", // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor ".ctor", // System_Runtime_InteropServices_LCIDConversionAttribute__ctor ".ctor", // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler "GetOrCreateEventRegistrationTokenTable", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable "InvocationList", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T "RemoveAllEventHandlers", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T ".ctor", // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 ".ctor", // System_Runtime_CompilerServices_ExtensionAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor ".ctor", // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 ".ctor", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor "WrapNonExceptionThrows", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows ".ctor", // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_FixedBufferAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags "Create", // System_Runtime_CompilerServices_CallSite_T__Create "Target", // System_Runtime_CompilerServices_CallSite_T__Target "GetObjectValue", // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject "InitializeArray", // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle "get_OffsetToStringData", // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData "GetSubArray", // System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T "Capture", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture "Throw", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw ".ctor", // System_Security_UnverifiableCodeAttribute__ctor "RequestMinimum", // System_Security_Permissions_SecurityAction__RequestMinimum ".ctor", // System_Security_Permissions_SecurityPermissionAttribute__ctor "SkipVerification", // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification "CreateInstance", // System_Activator__CreateInstance "CreateInstance", // System_Activator__CreateInstance_T "CompareExchange", // System_Threading_Interlocked__CompareExchange "CompareExchange", // System_Threading_Interlocked__CompareExchange_T "Enter", // System_Threading_Monitor__Enter "Enter", // System_Threading_Monitor__Enter2 "Exit", // System_Threading_Monitor__Exit "CurrentThread", // System_Threading_Thread__CurrentThread "ManagedThreadId", // System_Threading_Thread__ManagedThreadId "BinaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation "Convert", // Microsoft_CSharp_RuntimeBinder_Binder__Convert "GetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex "GetMember", // Microsoft_CSharp_RuntimeBinder_Binder__GetMember "Invoke", // Microsoft_CSharp_RuntimeBinder_Binder__Invoke "InvokeConstructor", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor "InvokeMember", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember "IsEvent", // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent "SetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex "SetMember", // Microsoft_CSharp_RuntimeBinder_Binder__SetMember "UnaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation "Create", // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject "ToGenericParameter", // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object "ChangeType", // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType "PlusObject", // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject "NegateObject", // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject "NotObject", // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject "AndObject", // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject "OrObject", // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject "XorObject", // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject "AddObject", // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject "SubtractObject", // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject "MultiplyObject", // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject "DivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject "ExponentObject", // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject "ModObject", // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject "IntDivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject "LeftShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject "RightShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject "ConcatenateObject", // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject "CompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean "CompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean "CompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean "CompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean "CompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean "CompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean "ConditionalCompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean "ConditionalCompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean "ConditionalCompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean "ConditionalCompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean "ConditionalCompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean "ConditionalCompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean "LateCall", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall "LateGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet "LateSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet "LateSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex "LateIndexGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet "LateIndexSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet "LateIndexSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex ".ctor", // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor ".ctor", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor "State", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State "MidStmtStr", // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr ".ctor", // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor ".ctor", // Microsoft_VisualBasic_Embedded__ctor "CopyArray", // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray "LikeString", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod "LikeObject", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod "CreateProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 "ClearProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError "EndApp", // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp "ForLoopInitObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj "ForNextCheckObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj "CheckForSyncLockOnValueType", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType "CallByName", // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName "IsNumeric", // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName "TypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName "VbTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName "IsNumeric", // Microsoft_VisualBasic_Information__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_Information__SystemTypeName "TypeName", // Microsoft_VisualBasic_Information__TypeName "VbTypeName", // Microsoft_VisualBasic_Information__VbTypeName "CallByName", // Microsoft_VisualBasic_Interaction__CallByName "MoveNext", // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext "SetStateMachine", // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task ".ctor", // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor "Asc", // Microsoft_VisualBasic_Strings__AscCharInt32 "Asc", // Microsoft_VisualBasic_Strings__AscStringInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWCharInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWStringInt32 "Chr", // Microsoft_VisualBasic_Strings__ChrInt32Char "ChrW", // Microsoft_VisualBasic_Strings__ChrWInt32Char ".ctor", // System_Xml_Linq_XElement__ctor ".ctor", // System_Xml_Linq_XElement__ctor2 "Get", // System_Xml_Linq_XNamespace__Get "Run", // System_Windows_Forms_Application__RunForm "CurrentManagedThreadId", // System_Environment__CurrentManagedThreadId ".ctor", // System_ComponentModel_EditorBrowsableAttribute__ctor "SustainedLowLatency", // System_Runtime_GCLatencyMode__SustainedLowLatency "Item1", // System_ValueTuple_T1__Item1 "Item1", // System_ValueTuple_T2__Item1 "Item2", // System_ValueTuple_T2__Item2 "Item1", // System_ValueTuple_T3__Item1 "Item2", // System_ValueTuple_T3__Item2 "Item3", // System_ValueTuple_T3__Item3 "Item1", // System_ValueTuple_T4__Item1 "Item2", // System_ValueTuple_T4__Item2 "Item3", // System_ValueTuple_T4__Item3 "Item4", // System_ValueTuple_T4__Item4 "Item1", // System_ValueTuple_T5__Item1 "Item2", // System_ValueTuple_T5__Item2 "Item3", // System_ValueTuple_T5__Item3 "Item4", // System_ValueTuple_T5__Item4 "Item5", // System_ValueTuple_T5__Item5 "Item1", // System_ValueTuple_T6__Item1 "Item2", // System_ValueTuple_T6__Item2 "Item3", // System_ValueTuple_T6__Item3 "Item4", // System_ValueTuple_T6__Item4 "Item5", // System_ValueTuple_T6__Item5 "Item6", // System_ValueTuple_T6__Item6 "Item1", // System_ValueTuple_T7__Item1 "Item2", // System_ValueTuple_T7__Item2 "Item3", // System_ValueTuple_T7__Item3 "Item4", // System_ValueTuple_T7__Item4 "Item5", // System_ValueTuple_T7__Item5 "Item6", // System_ValueTuple_T7__Item6 "Item7", // System_ValueTuple_T7__Item7 "Item1", // System_ValueTuple_TRest__Item1 "Item2", // System_ValueTuple_TRest__Item2 "Item3", // System_ValueTuple_TRest__Item3 "Item4", // System_ValueTuple_TRest__Item4 "Item5", // System_ValueTuple_TRest__Item5 "Item6", // System_ValueTuple_TRest__Item6 "Item7", // System_ValueTuple_TRest__Item7 "Rest", // System_ValueTuple_TRest__Rest ".ctor", // System_ValueTuple_T1__ctor ".ctor", // System_ValueTuple_T2__ctor ".ctor", // System_ValueTuple_T3__ctor ".ctor", // System_ValueTuple_T4__ctor ".ctor", // System_ValueTuple_T5__ctor ".ctor", // System_ValueTuple_T6__ctor ".ctor", // System_ValueTuple_T7__ctor ".ctor", // System_ValueTuple_TRest__ctor ".ctor", // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames "Format", // System_String__Format_IFormatProvider "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorByte ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags ".ctor", // System_Runtime_CompilerServices_NullableContextAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ObsoleteAttribute__ctor ".ctor", // System_Span__ctor "get_Item", // System_Span__get_Item "get_Length", // System_Span__get_Length ".ctor", // System_ReadOnlySpan__ctor "get_Item", // System_ReadOnlySpan__get_Item "get_Length", // System_ReadOnlySpan__get_Length ".ctor", // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor "Fix", // Microsoft_VisualBasic_Conversion__FixSingle "Fix", // Microsoft_VisualBasic_Conversion__FixDouble "Int", // Microsoft_VisualBasic_Conversion__IntSingle "Int", // Microsoft_VisualBasic_Conversion__IntDouble "Ceiling", // System_Math__CeilingDouble "Floor", // System_Math__FloorDouble "Truncate", // System_Math__TruncateDouble ".ctor", // System_Index__ctor "GetOffset", // System_Index__GetOffset ".ctor", // System_Range__ctor "StartAt", // System_Range__StartAt "EndAt", // System_Range__StartAt "get_All", // System_Range__get_All "get_Start", // System_Range__get_Start "get_End", // System_Range__get_End ".ctor", // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor "DisposeAsync", // System_IAsyncDisposable__DisposeAsync "GetAsyncEnumerator", // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator "MoveNextAsync", // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync "get_Current", // System_Collections_Generic_IAsyncEnumerator_T__get_Current "GetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted "Reset", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset "SetException", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException "SetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult "get_Version", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted ".ctor", // System_Threading_Tasks_ValueTask_T__ctor ".ctor", // System_Threading_Tasks_ValueTask_T__ctorValue ".ctor", // System_Threading_Tasks_ValueTask__ctor "Create", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create "Complete", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted "MoveNext", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T "get_Item", // System_Runtime_CompilerServices_ITuple__get_Item "get_Length", // System_Runtime_CompilerServices_ITuple__get_Length ".ctor", // System_InvalidOperationException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject "Equals", // System_Threading_CancellationToken__Equals "CreateLinkedTokenSource", // System_Threading_CancellationTokenSource__CreateLinkedTokenSource "Token", // System_Threading_CancellationTokenSource__Token "Dispose", // System_Threading_CancellationTokenSource__Dispose ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags "Append", // System_Text_StringBuilder__AppendString "Append", // System_Text_StringBuilder__AppendChar "Append", // System_Text_StringBuilder__AppendObject ".ctor", // System_Text_StringBuilder__ctor "ToStringAndClear", // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(WellKnownMember member) { return s_descriptors[(int)member]; } /// <summary> /// This function defines whether an attribute is optional or not. /// </summary> /// <param name="attributeMember">The attribute member.</param> internal static bool IsSynthesizedAttributeOptional(WellKnownMember attributeMember) { switch (attributeMember) { case WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes: case WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor: case WellKnownMember.System_STAThreadAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: return true; default: 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.Collections.Immutable; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class WellKnownMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static WellKnownMembers() { byte[] initializationBytes = new byte[] { // System_Math__RoundDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__PowDoubleDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Array__get_Length (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Array__Empty (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Convert__ToBooleanDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToBooleanInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Convert__ToBooleanUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Convert__ToBooleanInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Convert__ToBooleanUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Convert__ToBooleanSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToBooleanDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToSByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToSingleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToDoubleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_CLSCompliantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_CLSCompliantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_FlagsAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_FlagsAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Guid__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Guid, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Type__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Type__GetTypeFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Type__Missing (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Field Signature // System_Type__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Reflection_AssemblyKeyFileAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyFileAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_AssemblyKeyNameAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyNameAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_MethodBase__GetMethodFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, // System_Reflection_MethodBase__GetMethodFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_MethodInfo__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Reflection_MethodInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Delegate__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, // System_Delegate__CreateDelegate4 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Reflection_FieldInfo__GetFieldFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Reflection_FieldInfo__GetFieldFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_Missing__Value (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_Missing, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_Missing, // Field Signature // System_IEquatable_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_IEquatable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IEqualityComparer_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__get_Default (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T,// Return Type // System_AttributeUsageAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, 0, // System_AttributeUsageAttribute__AllowMultiple (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_AttributeUsageAttribute__Inherited (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_ParamArrayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ParamArrayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_STAThreadAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_STAThreadAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Reflection_DefaultMemberAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_DefaultMemberAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_Debugger__Break (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_Debugger, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerDisplayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_DebuggerDisplayAttribute__Type (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerHiddenAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableState, // System_Diagnostics_DebuggerStepThroughAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Runtime_InteropServices_UnknownWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnknownWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_DispatchWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispatchWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, // System_Runtime_InteropServices_CoClassAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_CoClassAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComAwareEventInfo__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComVisibleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DispIdAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispIdAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_GuidAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_GuidAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ComInterfaceType, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_Marshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_BestFitMappingAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_LCIDConversionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_CallingConvention, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Func_T2, 2, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ExtensionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_FixedBufferAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_DynamicAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_CallSite_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, // System_Runtime_CompilerServices_CallSite_T__Target (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices__GetSubArray_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_UnverifiableCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_UnverifiableCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_Permissions_SecurityAction__RequestMinimum (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Security_Permissions_SecurityAction, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // Field Signature // System_Security_Permissions_SecurityPermissionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Activator__CreateInstance (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Activator__CreateInstance_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Threading_Interlocked__CompareExchange (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Interlocked__CompareExchange_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Threading_Monitor__Enter (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Monitor__Enter2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Threading_Monitor__Exit (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Thread__CurrentThread (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Thread, // Return Type // System_Threading_Thread__ManagedThreadId (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Convert (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__GetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Invoke (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__SetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State (byte)MemberFlags.Field, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Field Signature // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Embedded__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_Embedded, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Interaction__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Interaction, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_Strings__AscCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__AscWCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscWStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__ChrInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_Strings__ChrWInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Xml_Linq_XElement__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XElement__ctor2 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XNamespace__Get (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Xml_Linq_XNamespace, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XNamespace, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Windows_Forms_Application__RunForm (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Windows_Forms_Application, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Windows_Forms_Form, // System_Environment__CurrentManagedThreadId (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Environment, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ComponentModel_EditorBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ComponentModel_EditorBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_ComponentModel_EditorBrowsableState, // System_Runtime_GCLatencyMode__SustainedLowLatency (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_GCLatencyMode, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_GCLatencyMode, // Field Signature // System_ValueTuple_T1__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T3__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T4__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T4__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T5__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T5__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T5__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T6__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T6__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T6__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T6__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T7__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T7__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T7__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T7__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T7__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_TRest__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_TRest__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_TRest__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_TRest__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_TRest__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_TRest__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Rest (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 7, // Field Signature // System_ValueTuple_T1__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_ValueTuple_T2__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, // System_ValueTuple_T3__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, // System_ValueTuple_T4__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, // System_ValueTuple_T_T2_T3_T4_T5__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, // System_ValueTuple_T6__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, // System_ValueTuple_T7__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, // System_ValueTuple_TRest__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, (byte)SignatureTypeCode.GenericTypeParameter, 7, // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_TupleElementNamesAttribute // DeclaringTypeId - WellKnownType.ExtSentinel), 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Format_IFormatProvider (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_IFormatProvider, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_NullableAttribute__ctorByte (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableContextAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ReferenceAssemblyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_ObsoleteAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ObsoleteAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Span__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ReadOnlySpan__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Conversion__FixSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__FixDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // Microsoft_VisualBasic_Conversion__IntSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__IntDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // System_Math__CeilingDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__FloorDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__TruncateDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Index__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Index__GetOffset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Range__ctor (byte)(MemberFlags.Constructor), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__StartAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__EndAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_All (byte)(MemberFlags.PropertyGet | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Range__get_Start (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_End (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_IAsyncDisposable__DisposeAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_IAsyncDisposable - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // Return Type: ValueTask // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: IAsyncEnumerator<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, // Argument: CancellationToken (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: ValueTask<bool> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_Generic_IAsyncEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_IValueTaskSource__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_ValueTask_T__ctorSourceAndToken (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: IValueTaskSource<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Threading_Tasks_ValueTask_T__ctorValue (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_ValueTask__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // Argument: IValueTaskSource (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_ITuple__get_Item (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ITuple__get_Length (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_InvalidOperationException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_InvalidOperationException - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_CancellationToken__Equals (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__CreateLinkedTokenSource (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__Token (byte)MemberFlags.Property, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Return Type // System_Threading_CancellationTokenSource__Dispose (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Text_StringBuilder__AppendString (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Text_StringBuilder__AppendChar (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Text_StringBuilder__AppendObject (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Text_StringBuilder__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type }; string[] allNames = new string[(int)WellKnownMember.Count] { "Round", // System_Math__RoundDouble "Pow", // System_Math__PowDoubleDouble "get_Length", // System_Array__get_Length "Empty", // System_Array__Empty "ToBoolean", // System_Convert__ToBooleanDecimal "ToBoolean", // System_Convert__ToBooleanInt32 "ToBoolean", // System_Convert__ToBooleanUInt32 "ToBoolean", // System_Convert__ToBooleanInt64 "ToBoolean", // System_Convert__ToBooleanUInt64 "ToBoolean", // System_Convert__ToBooleanSingle "ToBoolean", // System_Convert__ToBooleanDouble "ToSByte", // System_Convert__ToSByteDecimal "ToSByte", // System_Convert__ToSByteDouble "ToSByte", // System_Convert__ToSByteSingle "ToByte", // System_Convert__ToByteDecimal "ToByte", // System_Convert__ToByteDouble "ToByte", // System_Convert__ToByteSingle "ToInt16", // System_Convert__ToInt16Decimal "ToInt16", // System_Convert__ToInt16Double "ToInt16", // System_Convert__ToInt16Single "ToUInt16", // System_Convert__ToUInt16Decimal "ToUInt16", // System_Convert__ToUInt16Double "ToUInt16", // System_Convert__ToUInt16Single "ToInt32", // System_Convert__ToInt32Decimal "ToInt32", // System_Convert__ToInt32Double "ToInt32", // System_Convert__ToInt32Single "ToUInt32", // System_Convert__ToUInt32Decimal "ToUInt32", // System_Convert__ToUInt32Double "ToUInt32", // System_Convert__ToUInt32Single "ToInt64", // System_Convert__ToInt64Decimal "ToInt64", // System_Convert__ToInt64Double "ToInt64", // System_Convert__ToInt64Single "ToUInt64", // System_Convert__ToUInt64Decimal "ToUInt64", // System_Convert__ToUInt64Double "ToUInt64", // System_Convert__ToUInt64Single "ToSingle", // System_Convert__ToSingleDecimal "ToDouble", // System_Convert__ToDoubleDecimal ".ctor", // System_CLSCompliantAttribute__ctor ".ctor", // System_FlagsAttribute__ctor ".ctor", // System_Guid__ctor "GetTypeFromCLSID", // System_Type__GetTypeFromCLSID "GetTypeFromHandle", // System_Type__GetTypeFromHandle "Missing", // System_Type__Missing WellKnownMemberNames.EqualityOperatorName, // System_Type__op_Equality ".ctor", // System_Reflection_AssemblyKeyFileAttribute__ctor ".ctor", // System_Reflection_AssemblyKeyNameAttribute__ctor "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle2 "CreateDelegate", // System_Reflection_MethodInfo__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate4 "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle2 "Value", // System_Reflection_Missing__Value "Equals", // System_IEquatable_T__Equals "Equals", // System_Collections_Generic_IEqualityComparer_T__Equals "Equals", // System_Collections_Generic_EqualityComparer_T__Equals "GetHashCode", // System_Collections_Generic_EqualityComparer_T__GetHashCode "get_Default", // System_Collections_Generic_EqualityComparer_T__get_Default ".ctor", // System_AttributeUsageAttribute__ctor "AllowMultiple", // System_AttributeUsageAttribute__AllowMultiple "Inherited", // System_AttributeUsageAttribute__Inherited ".ctor", // System_ParamArrayAttribute__ctor ".ctor", // System_STAThreadAttribute__ctor ".ctor", // System_Reflection_DefaultMemberAttribute__ctor "Break", // System_Diagnostics_Debugger__Break ".ctor", // System_Diagnostics_DebuggerDisplayAttribute__ctor "Type", // System_Diagnostics_DebuggerDisplayAttribute__Type ".ctor", // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor ".ctor", // System_Diagnostics_DebuggerHiddenAttribute__ctor ".ctor", // System_Diagnostics_DebuggerBrowsableAttribute__ctor ".ctor", // System_Diagnostics_DebuggerStepThroughAttribute__ctor ".ctor", // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes "Default", // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default "DisableOptimizations", // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations "EnableEditAndContinue", // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue "IgnoreSymbolStoreSequencePoints", // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints ".ctor", // System_Runtime_InteropServices_UnknownWrapper__ctor ".ctor", // System_Runtime_InteropServices_DispatchWrapper__ctor ".ctor", // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType ".ctor", // System_Runtime_InteropServices_CoClassAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComAwareEventInfo__ctor "AddEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler "RemoveEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler ".ctor", // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString ".ctor", // System_Runtime_InteropServices_ComVisibleAttribute__ctor ".ctor", // System_Runtime_InteropServices_DispIdAttribute__ctor ".ctor", // System_Runtime_InteropServices_GuidAttribute__ctor ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 "GetTypeFromCLSID", // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString ".ctor", // System_Runtime_InteropServices_BestFitMappingAttribute__ctor ".ctor", // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor ".ctor", // System_Runtime_InteropServices_LCIDConversionAttribute__ctor ".ctor", // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler "GetOrCreateEventRegistrationTokenTable", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable "InvocationList", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T "RemoveAllEventHandlers", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T ".ctor", // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 ".ctor", // System_Runtime_CompilerServices_ExtensionAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor ".ctor", // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 ".ctor", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor "WrapNonExceptionThrows", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows ".ctor", // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_FixedBufferAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags "Create", // System_Runtime_CompilerServices_CallSite_T__Create "Target", // System_Runtime_CompilerServices_CallSite_T__Target "GetObjectValue", // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject "InitializeArray", // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle "get_OffsetToStringData", // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData "GetSubArray", // System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T "Capture", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture "Throw", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw ".ctor", // System_Security_UnverifiableCodeAttribute__ctor "RequestMinimum", // System_Security_Permissions_SecurityAction__RequestMinimum ".ctor", // System_Security_Permissions_SecurityPermissionAttribute__ctor "SkipVerification", // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification "CreateInstance", // System_Activator__CreateInstance "CreateInstance", // System_Activator__CreateInstance_T "CompareExchange", // System_Threading_Interlocked__CompareExchange "CompareExchange", // System_Threading_Interlocked__CompareExchange_T "Enter", // System_Threading_Monitor__Enter "Enter", // System_Threading_Monitor__Enter2 "Exit", // System_Threading_Monitor__Exit "CurrentThread", // System_Threading_Thread__CurrentThread "ManagedThreadId", // System_Threading_Thread__ManagedThreadId "BinaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation "Convert", // Microsoft_CSharp_RuntimeBinder_Binder__Convert "GetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex "GetMember", // Microsoft_CSharp_RuntimeBinder_Binder__GetMember "Invoke", // Microsoft_CSharp_RuntimeBinder_Binder__Invoke "InvokeConstructor", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor "InvokeMember", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember "IsEvent", // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent "SetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex "SetMember", // Microsoft_CSharp_RuntimeBinder_Binder__SetMember "UnaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation "Create", // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject "ToGenericParameter", // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object "ChangeType", // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType "PlusObject", // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject "NegateObject", // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject "NotObject", // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject "AndObject", // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject "OrObject", // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject "XorObject", // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject "AddObject", // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject "SubtractObject", // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject "MultiplyObject", // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject "DivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject "ExponentObject", // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject "ModObject", // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject "IntDivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject "LeftShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject "RightShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject "ConcatenateObject", // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject "CompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean "CompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean "CompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean "CompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean "CompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean "CompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean "ConditionalCompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean "ConditionalCompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean "ConditionalCompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean "ConditionalCompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean "ConditionalCompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean "ConditionalCompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean "LateCall", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall "LateGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet "LateSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet "LateSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex "LateIndexGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet "LateIndexSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet "LateIndexSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex ".ctor", // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor ".ctor", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor "State", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State "MidStmtStr", // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr ".ctor", // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor ".ctor", // Microsoft_VisualBasic_Embedded__ctor "CopyArray", // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray "LikeString", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod "LikeObject", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod "CreateProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 "ClearProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError "EndApp", // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp "ForLoopInitObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj "ForNextCheckObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj "CheckForSyncLockOnValueType", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType "CallByName", // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName "IsNumeric", // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName "TypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName "VbTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName "IsNumeric", // Microsoft_VisualBasic_Information__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_Information__SystemTypeName "TypeName", // Microsoft_VisualBasic_Information__TypeName "VbTypeName", // Microsoft_VisualBasic_Information__VbTypeName "CallByName", // Microsoft_VisualBasic_Interaction__CallByName "MoveNext", // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext "SetStateMachine", // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task ".ctor", // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor "Asc", // Microsoft_VisualBasic_Strings__AscCharInt32 "Asc", // Microsoft_VisualBasic_Strings__AscStringInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWCharInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWStringInt32 "Chr", // Microsoft_VisualBasic_Strings__ChrInt32Char "ChrW", // Microsoft_VisualBasic_Strings__ChrWInt32Char ".ctor", // System_Xml_Linq_XElement__ctor ".ctor", // System_Xml_Linq_XElement__ctor2 "Get", // System_Xml_Linq_XNamespace__Get "Run", // System_Windows_Forms_Application__RunForm "CurrentManagedThreadId", // System_Environment__CurrentManagedThreadId ".ctor", // System_ComponentModel_EditorBrowsableAttribute__ctor "SustainedLowLatency", // System_Runtime_GCLatencyMode__SustainedLowLatency "Item1", // System_ValueTuple_T1__Item1 "Item1", // System_ValueTuple_T2__Item1 "Item2", // System_ValueTuple_T2__Item2 "Item1", // System_ValueTuple_T3__Item1 "Item2", // System_ValueTuple_T3__Item2 "Item3", // System_ValueTuple_T3__Item3 "Item1", // System_ValueTuple_T4__Item1 "Item2", // System_ValueTuple_T4__Item2 "Item3", // System_ValueTuple_T4__Item3 "Item4", // System_ValueTuple_T4__Item4 "Item1", // System_ValueTuple_T5__Item1 "Item2", // System_ValueTuple_T5__Item2 "Item3", // System_ValueTuple_T5__Item3 "Item4", // System_ValueTuple_T5__Item4 "Item5", // System_ValueTuple_T5__Item5 "Item1", // System_ValueTuple_T6__Item1 "Item2", // System_ValueTuple_T6__Item2 "Item3", // System_ValueTuple_T6__Item3 "Item4", // System_ValueTuple_T6__Item4 "Item5", // System_ValueTuple_T6__Item5 "Item6", // System_ValueTuple_T6__Item6 "Item1", // System_ValueTuple_T7__Item1 "Item2", // System_ValueTuple_T7__Item2 "Item3", // System_ValueTuple_T7__Item3 "Item4", // System_ValueTuple_T7__Item4 "Item5", // System_ValueTuple_T7__Item5 "Item6", // System_ValueTuple_T7__Item6 "Item7", // System_ValueTuple_T7__Item7 "Item1", // System_ValueTuple_TRest__Item1 "Item2", // System_ValueTuple_TRest__Item2 "Item3", // System_ValueTuple_TRest__Item3 "Item4", // System_ValueTuple_TRest__Item4 "Item5", // System_ValueTuple_TRest__Item5 "Item6", // System_ValueTuple_TRest__Item6 "Item7", // System_ValueTuple_TRest__Item7 "Rest", // System_ValueTuple_TRest__Rest ".ctor", // System_ValueTuple_T1__ctor ".ctor", // System_ValueTuple_T2__ctor ".ctor", // System_ValueTuple_T3__ctor ".ctor", // System_ValueTuple_T4__ctor ".ctor", // System_ValueTuple_T5__ctor ".ctor", // System_ValueTuple_T6__ctor ".ctor", // System_ValueTuple_T7__ctor ".ctor", // System_ValueTuple_TRest__ctor ".ctor", // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames "Format", // System_String__Format_IFormatProvider "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorByte ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags ".ctor", // System_Runtime_CompilerServices_NullableContextAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ObsoleteAttribute__ctor ".ctor", // System_Span__ctor "get_Item", // System_Span__get_Item "get_Length", // System_Span__get_Length ".ctor", // System_ReadOnlySpan__ctor "get_Item", // System_ReadOnlySpan__get_Item "get_Length", // System_ReadOnlySpan__get_Length ".ctor", // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor "Fix", // Microsoft_VisualBasic_Conversion__FixSingle "Fix", // Microsoft_VisualBasic_Conversion__FixDouble "Int", // Microsoft_VisualBasic_Conversion__IntSingle "Int", // Microsoft_VisualBasic_Conversion__IntDouble "Ceiling", // System_Math__CeilingDouble "Floor", // System_Math__FloorDouble "Truncate", // System_Math__TruncateDouble ".ctor", // System_Index__ctor "GetOffset", // System_Index__GetOffset ".ctor", // System_Range__ctor "StartAt", // System_Range__StartAt "EndAt", // System_Range__StartAt "get_All", // System_Range__get_All "get_Start", // System_Range__get_Start "get_End", // System_Range__get_End ".ctor", // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor "DisposeAsync", // System_IAsyncDisposable__DisposeAsync "GetAsyncEnumerator", // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator "MoveNextAsync", // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync "get_Current", // System_Collections_Generic_IAsyncEnumerator_T__get_Current "GetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted "Reset", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset "SetException", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException "SetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult "get_Version", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted ".ctor", // System_Threading_Tasks_ValueTask_T__ctor ".ctor", // System_Threading_Tasks_ValueTask_T__ctorValue ".ctor", // System_Threading_Tasks_ValueTask__ctor "Create", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create "Complete", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted "MoveNext", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T "get_Item", // System_Runtime_CompilerServices_ITuple__get_Item "get_Length", // System_Runtime_CompilerServices_ITuple__get_Length ".ctor", // System_InvalidOperationException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject "Equals", // System_Threading_CancellationToken__Equals "CreateLinkedTokenSource", // System_Threading_CancellationTokenSource__CreateLinkedTokenSource "Token", // System_Threading_CancellationTokenSource__Token "Dispose", // System_Threading_CancellationTokenSource__Dispose ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags "Append", // System_Text_StringBuilder__AppendString "Append", // System_Text_StringBuilder__AppendChar "Append", // System_Text_StringBuilder__AppendObject ".ctor", // System_Text_StringBuilder__ctor "ToStringAndClear", // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(WellKnownMember member) { return s_descriptors[(int)member]; } /// <summary> /// This function defines whether an attribute is optional or not. /// </summary> /// <param name="attributeMember">The attribute member.</param> internal static bool IsSynthesizedAttributeOptional(WellKnownMember attributeMember) { switch (attributeMember) { case WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes: case WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor: case WellKnownMember.System_STAThreadAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: return true; default: return false; } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Diagnostics/MakeMethodSynchronous/MakeMethodSynchronousTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous.CSharpMakeMethodSynchronousCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodSynchronous { public class MakeMethodSynchronousTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTaskReturnType() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTaskOfTReturnType() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task<int> {|CS1998:Goo|}() { return 1; } }", @" using System.Threading.Tasks; class C { int {|#0:Goo|}() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestSecondModifier() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { public async Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { public void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestFirstModifier() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async public Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { public void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTrailingTrivia() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async // comment Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestRenameMethod() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:GooAsync|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestRenameMethod1() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:GooAsync|}() { } void Bar() { GooAsync(); } }", @" using System.Threading.Tasks; class C { void Goo() { } void Bar() { Goo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestParenthesizedLambda() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = async () {|CS1998:=>|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = () {|#0:=>|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,16): error CS1643: Not all code paths return a value in lambda expression of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestSimpleLambda() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task> f = async a {|CS1998:=>|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task> f = a {|#0:=>|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestLambdaWithExpressionBody() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task<int>> f = async a {|CS1998:=>|} 1; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task<int>> f = a => {|#0:1|}; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,18): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' DiagnosticResult.CompilerError("CS0029").WithLocation(0).WithArguments("int", "System.Threading.Tasks.Task<int>"), // /0/Test0.cs(10,18): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type DiagnosticResult.CompilerError("CS1662").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestAnonymousMethod() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = async {|CS1998:delegate|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = {|#0:delegate|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,13): error CS1643: Not all code paths return a value in anonymous method of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestFixAll() { await VerifyCS.VerifyCodeFixAsync( @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { BarAsync(); } async Task<int> {|#0:{|CS1998:BarAsync|}|}() { GooAsync(); return 1; } }", @"using System.Threading.Tasks; public class Class1 { void Goo() { Bar(); } int {|#0:Bar|}() { Goo(); return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller1() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await GooAsync(); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller2() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await GooAsync().ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller3() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await this.GooAsync(); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { this.Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller4() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await this.GooAsync().ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { this.Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested1() { var source = @"using System.Threading.Tasks; public class Class1 { async Task<int> {|CS1998:GooAsync|}(int i) { return 1; } async void BarAsync() { await this.GooAsync(await this.GooAsync(0)); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { int Goo(int i) { return 1; } async void {|CS1998:BarAsync|}() { this.Goo(this.Goo(0)); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested() { var source = @"using System.Threading.Tasks; public class Class1 { async Task<int> {|CS1998:GooAsync|}(int i) { return 1; } async void BarAsync() { await this.GooAsync(await this.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { int Goo(int i) { return 1; } async void {|CS1998:BarAsync|}() { this.Goo(this.Goo(0)); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task RemoveAsyncInLocalFunction() { await VerifyCS.VerifyCodeFixAsync( @"using System.Threading.Tasks; class C { public void M1() { async Task {|CS1998:M2Async|}() { } } }", @"using System.Threading.Tasks; class C { public void M1() { void M2() { } } }"); } [Theory] [InlineData("Task<C>", "C")] [InlineData("Task<int>", "int")] [InlineData("Task", "void")] [InlineData("void", "void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] public async Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn) { await VerifyCS.VerifyCodeFixAsync( $@"using System; using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }} }}", $@"using System; using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {expectedReturn} /*2*/ M2/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }} }}"); } [Theory] [InlineData("", "Task<C>", "\r\n C")] [InlineData("", "Task<int>", "\r\n int")] [InlineData("", "Task", "\r\n void")] [InlineData("", "void", "\r\n void")] [InlineData("public", "Task<C>", " C")] [InlineData("public", "Task<int>", " int")] [InlineData("public", "Task", " void")] [InlineData("public", "void", " void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] public async Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn) { await VerifyCS.VerifyCodeFixAsync( $@"using System; using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }}", $@"using System; using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/{expectedReturn} /*2*/ M2/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithUsingAwait() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await using ({|#0:var x = new object()|}) { } } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(5,22): error CS8410: 'object': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. DiagnosticResult.CompilerError("CS8410").WithLocation(0).WithArguments("object"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithUsingNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { using ({|#0:var x = new object()|}) { } } }", // /0/Test0.cs(5,16): error CS1674: 'object': type used in a using statement must be implicitly convertible to 'System.IDisposable'. DiagnosticResult.CompilerError("CS1674").WithLocation(0).WithArguments("object"), @"class C { void M() { using ({|#0:var x = new object()|}) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithAwaitForEach() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await foreach (var n in {|#0:new int[] { }|}) { } } }"; await VerifyCS.VerifyCodeFixAsync( source, // /0/Test0.cs(5,33): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"), source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { foreach (var n in new int[] { }) { } } }", @"class C { void M() { foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachVariableAwait() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await foreach (var (a, b) in {|#0:new(int, int)[] { }|}) { } } }"; await VerifyCS.VerifyCodeFixAsync( source, // /0/Test0.cs(5,38): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"), source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachVariableNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { foreach (var (a, b) in new(int, int)[] { }) { } } }", @"class C { void M() { foreach (var (a, b) in new (int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestIAsyncEnumerableReturnType() { var source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { async IAsyncEnumerable<int> {|CS1998:MAsync|}() { yield return 1; } }"; var expected = @" using System.Threading.Tasks; using System.Collections.Generic; class C { IEnumerable<int> M() { yield return 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, FixedCode = expected, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestIAsyncEnumeratorReturnTypeOnLocalFunction() { var source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { void Method() { async IAsyncEnumerator<int> {|CS1998:MAsync|}() { yield return 1; } } }"; var expected = @" using System.Threading.Tasks; using System.Collections.Generic; class C { void Method() { IEnumerator<int> M() { yield return 1; } } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, FixedCode = expected, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous.CSharpMakeMethodSynchronousCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.MakeMethodSynchronous { public class MakeMethodSynchronousTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTaskReturnType() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTaskOfTReturnType() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task<int> {|CS1998:Goo|}() { return 1; } }", @" using System.Threading.Tasks; class C { int {|#0:Goo|}() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestSecondModifier() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { public async Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { public void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestFirstModifier() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async public Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { public void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestTrailingTrivia() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async // comment Task {|CS1998:Goo|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestRenameMethod() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:GooAsync|}() { } }", @" using System.Threading.Tasks; class C { void Goo() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestRenameMethod1() { await VerifyCS.VerifyCodeFixAsync( @" using System.Threading.Tasks; class C { async Task {|CS1998:GooAsync|}() { } void Bar() { GooAsync(); } }", @" using System.Threading.Tasks; class C { void Goo() { } void Bar() { Goo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestParenthesizedLambda() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = async () {|CS1998:=>|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = () {|#0:=>|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,16): error CS1643: Not all code paths return a value in lambda expression of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestSimpleLambda() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task> f = async a {|CS1998:=>|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task> f = a {|#0:=>|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,15): error CS1643: Not all code paths return a value in lambda expression of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestLambdaWithExpressionBody() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task<int>> f = async a {|CS1998:=>|} 1; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<string, Task<int>> f = a => {|#0:1|}; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,18): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' DiagnosticResult.CompilerError("CS0029").WithLocation(0).WithArguments("int", "System.Threading.Tasks.Task<int>"), // /0/Test0.cs(10,18): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type DiagnosticResult.CompilerError("CS1662").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestAnonymousMethod() { var source = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = async {|CS1998:delegate|} { }; } }"; var expected = @" using System; using System.Threading.Tasks; class C { void Goo() { Func<Task> f = {|#0:delegate|} { }; } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, ExpectedDiagnostics = { // /0/Test0.cs(10,13): error CS1643: Not all code paths return a value in anonymous method of type 'Func<Task>' DiagnosticResult.CompilerError("CS1643").WithLocation(0), }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestFixAll() { await VerifyCS.VerifyCodeFixAsync( @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { BarAsync(); } async Task<int> {|#0:{|CS1998:BarAsync|}|}() { GooAsync(); return 1; } }", @"using System.Threading.Tasks; public class Class1 { void Goo() { Bar(); } int {|#0:Bar|}() { Goo(); return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller1() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await GooAsync(); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller2() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await GooAsync().ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller3() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await this.GooAsync(); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { this.Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCaller4() { var source = @"using System.Threading.Tasks; public class Class1 { async Task {|CS1998:GooAsync|}() { } async void BarAsync() { await this.GooAsync().ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { void Goo() { } async void {|CS1998:BarAsync|}() { this.Goo(); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested1() { var source = @"using System.Threading.Tasks; public class Class1 { async Task<int> {|CS1998:GooAsync|}(int i) { return 1; } async void BarAsync() { await this.GooAsync(await this.GooAsync(0)); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { int Goo(int i) { return 1; } async void {|CS1998:BarAsync|}() { this.Goo(this.Goo(0)); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] [WorkItem(13961, "https://github.com/dotnet/roslyn/issues/13961")] public async Task TestRemoveAwaitFromCallerNested() { var source = @"using System.Threading.Tasks; public class Class1 { async Task<int> {|CS1998:GooAsync|}(int i) { return 1; } async void BarAsync() { await this.GooAsync(await this.GooAsync(0).ConfigureAwait(false)).ConfigureAwait(false); } }"; var expected = @"using System.Threading.Tasks; public class Class1 { int Goo(int i) { return 1; } async void {|CS1998:BarAsync|}() { this.Goo(this.Goo(0)); } }"; await new VerifyCS.Test { TestCode = source, FixedState = { Sources = { expected }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(14133, "https://github.com/dotnet/roslyn/issues/14133")] public async Task RemoveAsyncInLocalFunction() { await VerifyCS.VerifyCodeFixAsync( @"using System.Threading.Tasks; class C { public void M1() { async Task {|CS1998:M2Async|}() { } } }", @"using System.Threading.Tasks; class C { public void M1() { void M2() { } } }"); } [Theory] [InlineData("Task<C>", "C")] [InlineData("Task<int>", "int")] [InlineData("Task", "void")] [InlineData("void", "void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] public async Task RemoveAsyncInLocalFunctionKeepsTrivia(string asyncReturn, string expectedReturn) { await VerifyCS.VerifyCodeFixAsync( $@"using System; using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }} }}", $@"using System; using System.Threading.Tasks; class C {{ public void M1() {{ // Leading trivia /*1*/ {expectedReturn} /*2*/ M2/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }} }}"); } [Theory] [InlineData("", "Task<C>", "\r\n C")] [InlineData("", "Task<int>", "\r\n int")] [InlineData("", "Task", "\r\n void")] [InlineData("", "void", "\r\n void")] [InlineData("public", "Task<C>", " C")] [InlineData("public", "Task<int>", " int")] [InlineData("public", "Task", " void")] [InlineData("public", "void", " void")] [Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodAsynchronous)] [WorkItem(18307, "https://github.com/dotnet/roslyn/issues/18307")] public async Task RemoveAsyncKeepsTrivia(string modifiers, string asyncReturn, string expectedReturn) { await VerifyCS.VerifyCodeFixAsync( $@"using System; using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/ async {asyncReturn} /*2*/ {{|CS1998:M2Async|}}/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }}", $@"using System; using System.Threading.Tasks; class C {{ // Leading trivia {modifiers}/*1*/{expectedReturn} /*2*/ M2/*3*/() /*4*/ {{ throw new NotImplementedException(); }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithUsingAwait() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await using ({|#0:var x = new object()|}) { } } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, ExpectedDiagnostics = { // /0/Test0.cs(5,22): error CS8410: 'object': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. DiagnosticResult.CompilerError("CS8410").WithLocation(0).WithArguments("object"), }, FixedCode = source, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithUsingNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { using ({|#0:var x = new object()|}) { } } }", // /0/Test0.cs(5,16): error CS1674: 'object': type used in a using statement must be implicitly convertible to 'System.IDisposable'. DiagnosticResult.CompilerError("CS1674").WithLocation(0).WithArguments("object"), @"class C { void M() { using ({|#0:var x = new object()|}) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithAwaitForEach() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await foreach (var n in {|#0:new int[] { }|}) { } } }"; await VerifyCS.VerifyCodeFixAsync( source, // /0/Test0.cs(5,33): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"), source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { foreach (var n in new int[] { }) { } } }", @"class C { void M() { foreach (var n in new int[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachVariableAwait() { var source = @"class C { async System.Threading.Tasks.Task MAsync() { await foreach (var (a, b) in {|#0:new(int, int)[] { }|}) { } } }"; await VerifyCS.VerifyCodeFixAsync( source, // /0/Test0.cs(5,38): error CS1061: 'bool' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?) DiagnosticResult.CompilerError("CS1061").WithLocation(0).WithArguments("bool", "GetAwaiter"), source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task MethodWithForEachVariableNoAwait() { await VerifyCS.VerifyCodeFixAsync( @"class C { async System.Threading.Tasks.Task {|CS1998:MAsync|}() { foreach (var (a, b) in new(int, int)[] { }) { } } }", @"class C { void M() { foreach (var (a, b) in new (int, int)[] { }) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestIAsyncEnumerableReturnType() { var source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { async IAsyncEnumerable<int> {|CS1998:MAsync|}() { yield return 1; } }"; var expected = @" using System.Threading.Tasks; using System.Collections.Generic; class C { IEnumerable<int> M() { yield return 1; } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, FixedCode = expected, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeMethodSynchronous)] public async Task TestIAsyncEnumeratorReturnTypeOnLocalFunction() { var source = @" using System.Threading.Tasks; using System.Collections.Generic; class C { void Method() { async IAsyncEnumerator<int> {|CS1998:MAsync|}() { yield return 1; } } }"; var expected = @" using System.Threading.Tasks; using System.Collections.Generic; class C { void Method() { IEnumerator<int> M() { yield return 1; } } }"; await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21, TestCode = source, FixedCode = expected, }.RunAsync(); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Embedded.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Embedded : CSharpTestBase { [Fact] public void ReferencingEmbeddedAttributesFromTheSameAssemblySucceeds() { var code = @" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } } class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); } }"; CreateCompilation(code).VerifyEmitDiagnostics(); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Internal() { var reference = CreateCompilation(@" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Source"")] namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Module() { var module = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }", options: TestOptions.ReleaseModule); var reference = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Public() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] public class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestType2 { } public class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }).VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void EmbeddedAttributeInSourceIsAllowedIfCompilerDoesNotNeedToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestReference { public static int GetValue() => 3; } } class Test { public static void Main() { // This should be fine, as the compiler doesn't need to use an embedded attribute for this compilation System.Console.Write(OtherNamespace.TestReference.GetValue()); } }"; CompileAndVerify(code, verify: Verification.Passes, expectedOutput: "3"); } [Fact] public void EmbeddedAttributeInSourceShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, assemblyName: "testModule").VerifyEmitDiagnostics( // (4,18): error CS8336: The type name 'Microsoft.CodeAnalysis.EmbeddedAttribute' is reserved to be used by the compiler. // public class EmbeddedAttribute : System.Attribute { } Diagnostic(ErrorCode.ERR_TypeReserved, "EmbeddedAttribute").WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(4, 18)); } [Fact] public void EmbeddedAttributeInReferencedModuleShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var module = CreateCompilation(options: TestOptions.ReleaseModule, assemblyName: "testModule", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }"); var moduleRef = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { moduleRef }).VerifyEmitDiagnostics( // error CS8004: Type 'EmbeddedAttribute' exported from module 'testModule.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute", "testModule.netmodule").WithLocation(1, 1)); } [Fact] public void EmbeddedAttributeForwardedToAnotherAssemblyShouldTriggerAnError() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }", assemblyName: "reference").ToMetadataReference(); var code = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(Microsoft.CodeAnalysis.EmbeddedAttribute))] class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { reference }).VerifyEmitDiagnostics( // error CS8006: Forwarded type 'EmbeddedAttribute' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(1, 1)); } [Fact] public void CompilerShouldIgnorePublicEmbeddedAttributesInReferencedAssemblies() { var reference = CreateCompilation(assemblyName: "testRef", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { public class TestReference { } }").ToMetadataReference(); var code = @" class Test { // This should trigger generating another EmbeddedAttribute public void M(in int p) { var obj = new OtherNamespace.TestReference(); // This should be fine } }"; CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module => { var attributeName = AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName; var referenceAttribute = module.GetReferencedAssemblySymbols().Single(assembly => assembly.Name == "testRef").GetTypeByMetadataName(attributeName); Assert.NotNull(referenceAttribute); var generatedAttribute = module.ContainingAssembly.GetTypeByMetadataName(attributeName); Assert.NotNull(generatedAttribute); Assert.False(referenceAttribute.Equals(generatedAttribute)); }); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NonExisting() { var code = @" namespace System { public class Object {} public class Void {} } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemObject() { var code = @" namespace System { public class Attribute {} public class Void {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (5,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Void {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Void").WithArguments("System.Object").WithLocation(5, 18), // (7,14): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object").WithLocation(7, 14), // (4,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Object").WithLocation(4, 18), // (9,24): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 24), // (9,12): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 12), // (4,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Attribute {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Attribute").WithArguments("object", "0").WithLocation(4, 18), // (5,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Void {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Void").WithArguments("object", "0").WithLocation(5, 18), // (7,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0").WithLocation(7, 14)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemVoid() { var code = @" namespace System { public class Attribute {} public class Object {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (4,18): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Void").WithLocation(4, 18), // (7,14): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Void").WithLocation(7, 14), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoDefaultConstructor() { var code = @" namespace System { public class Object {} public class Void {} public class Attribute { public Attribute(object p) { } } } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1)); } [Fact] public void EmbeddedTypesInAnAssemblyAreNotExposedExternally() { var compilation1 = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } [Microsoft.CodeAnalysis.Embedded] public class TestReference1 { } public class TestReference2 { } "); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference2")); var compilation2 = CreateCompilation("", references: new[] { compilation1.EmitToImageReference() }); Assert.Null(compilation2.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation2.GetTypeByMetadataName("TestReference2")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Embedded : CSharpTestBase { [Fact] public void ReferencingEmbeddedAttributesFromTheSameAssemblySucceeds() { var code = @" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } } class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); } }"; CreateCompilation(code).VerifyEmitDiagnostics(); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Internal() { var reference = CreateCompilation(@" [assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Source"")] namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Module() { var module = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] internal class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] internal class TestType2 { } internal class TestType3 { } }", options: TestOptions.ReleaseModule); var reference = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference }, assemblyName: "Source").VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void ReferencingEmbeddedAttributesFromADifferentAssemblyFails_Public() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { internal class EmbeddedAttribute : System.Attribute { } } namespace TestReference { [Microsoft.CodeAnalysis.Embedded] public class TestType1 { } [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestType2 { } public class TestType3 { } }"); var code = @" class Program { public static void Main() { var obj1 = new TestReference.TestType1(); var obj2 = new TestReference.TestType2(); var obj3 = new TestReference.TestType3(); // This should be fine } }"; CreateCompilation(code, references: new[] { reference.ToMetadataReference() }).VerifyDiagnostics( // (6,38): error CS0234: The type or namespace name 'TestType1' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj1 = new TestReference.TestType1(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType1").WithArguments("TestType1", "TestReference").WithLocation(6, 38), // (7,38): error CS0234: The type or namespace name 'TestType2' does not exist in the namespace 'TestReference' (are you missing an assembly reference?) // var obj2 = new TestReference.TestType2(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType2").WithArguments("TestType2", "TestReference").WithLocation(7, 38)); } [Fact] public void EmbeddedAttributeInSourceIsAllowedIfCompilerDoesNotNeedToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { [Microsoft.CodeAnalysis.EmbeddedAttribute] public class TestReference { public static int GetValue() => 3; } } class Test { public static void Main() { // This should be fine, as the compiler doesn't need to use an embedded attribute for this compilation System.Console.Write(OtherNamespace.TestReference.GetValue()); } }"; CompileAndVerify(code, verify: Verification.Passes, expectedOutput: "3"); } [Fact] public void EmbeddedAttributeInSourceShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var code = @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, assemblyName: "testModule").VerifyEmitDiagnostics( // (4,18): error CS8336: The type name 'Microsoft.CodeAnalysis.EmbeddedAttribute' is reserved to be used by the compiler. // public class EmbeddedAttribute : System.Attribute { } Diagnostic(ErrorCode.ERR_TypeReserved, "EmbeddedAttribute").WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(4, 18)); } [Fact] public void EmbeddedAttributeInReferencedModuleShouldTriggerAnErrorIfCompilerNeedsToGenerateOne() { var module = CreateCompilation(options: TestOptions.ReleaseModule, assemblyName: "testModule", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }"); var moduleRef = ModuleMetadata.CreateFromImage(module.EmitToArray()).GetReference(); var code = @" class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { moduleRef }).VerifyEmitDiagnostics( // error CS8004: Type 'EmbeddedAttribute' exported from module 'testModule.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute", "testModule.netmodule").WithLocation(1, 1)); } [Fact] public void EmbeddedAttributeForwardedToAnotherAssemblyShouldTriggerAnError() { var reference = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } }", assemblyName: "reference").ToMetadataReference(); var code = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(Microsoft.CodeAnalysis.EmbeddedAttribute))] class Test { public void M(in int p) { // This should trigger generating another EmbeddedAttribute } }"; CreateCompilation(code, references: new[] { reference }).VerifyEmitDiagnostics( // error CS8006: Forwarded type 'EmbeddedAttribute' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("Microsoft.CodeAnalysis.EmbeddedAttribute").WithLocation(1, 1)); } [Fact] public void CompilerShouldIgnorePublicEmbeddedAttributesInReferencedAssemblies() { var reference = CreateCompilation(assemblyName: "testRef", source: @" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } namespace OtherNamespace { public class TestReference { } }").ToMetadataReference(); var code = @" class Test { // This should trigger generating another EmbeddedAttribute public void M(in int p) { var obj = new OtherNamespace.TestReference(); // This should be fine } }"; CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module => { var attributeName = AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName; var referenceAttribute = module.GetReferencedAssemblySymbols().Single(assembly => assembly.Name == "testRef").GetTypeByMetadataName(attributeName); Assert.NotNull(referenceAttribute); var generatedAttribute = module.ContainingAssembly.GetTypeByMetadataName(attributeName); Assert.NotNull(generatedAttribute); Assert.False(referenceAttribute.Equals(generatedAttribute)); }); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NonExisting() { var code = @" namespace System { public class Object {} public class Void {} } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemObject() { var code = @" namespace System { public class Attribute {} public class Void {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (5,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Void {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Void").WithArguments("System.Object").WithLocation(5, 18), // (7,14): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object").WithLocation(7, 14), // (4,18): error CS0518: Predefined type 'System.Object' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Object").WithLocation(4, 18), // (9,24): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 24), // (9,12): error CS0518: Predefined type 'System.Object' is not defined or imported // public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Object").WithLocation(9, 12), // (4,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Attribute {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Attribute").WithArguments("object", "0").WithLocation(4, 18), // (5,18): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Void {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Void").WithArguments("object", "0").WithLocation(5, 18), // (7,14): error CS1729: 'object' does not contain a constructor that takes 0 arguments // public class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0").WithLocation(7, 14)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoSystemVoid() { var code = @" namespace System { public class Attribute {} public class Object {} } public class Test { public object M(in object x) { return x; } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // (4,18): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Attribute {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Attribute").WithArguments("System.Void").WithLocation(4, 18), // (7,14): error CS0518: Predefined type 'System.Void' is not defined or imported // public class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Void").WithLocation(7, 14), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1)); } [Fact] public void SynthesizingAttributeRequiresSystemAttribute_NoDefaultConstructor() { var code = @" namespace System { public class Object {} public class Void {} public class Attribute { public Attribute(object p) { } } } public class Test { public void M(in object x) { } // should trigger synthesizing IsReadOnly }"; CreateEmptyCompilation(code).VerifyEmitDiagnostics(CodeAnalysis.Emit.EmitOptions.Default.WithRuntimeMetadataVersion("v4.0.30319"), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1), // error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1)); } [Fact] public void EmbeddedTypesInAnAssemblyAreNotExposedExternally() { var compilation1 = CreateCompilation(@" namespace Microsoft.CodeAnalysis { public class EmbeddedAttribute : System.Attribute { } } [Microsoft.CodeAnalysis.Embedded] public class TestReference1 { } public class TestReference2 { } "); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation1.GetTypeByMetadataName("TestReference2")); var compilation2 = CreateCompilation("", references: new[] { compilation1.EmitToImageReference() }); Assert.Null(compilation2.GetTypeByMetadataName("TestReference1")); Assert.NotNull(compilation2.GetTypeByMetadataName("TestReference2")); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (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. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExtractMethod/AbstractSyntaxTriviaService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class AbstractSyntaxTriviaService : ISyntaxTriviaService { private const int TriviaLocationsCount = 4; private readonly ISyntaxFacts _syntaxFacts; private readonly int _endOfLineKind; protected AbstractSyntaxTriviaService(ISyntaxFacts syntaxFacts, int endOfLineKind) { _syntaxFacts = syntaxFacts; _endOfLineKind = endOfLineKind; } public ITriviaSavedResult SaveTriviaAroundSelection(SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); Debug.Assert(Enum.GetNames(typeof(TriviaLocation)).Length == TriviaLocationsCount); var tokens = GetTokensAtEdges(root, textSpan); // span must contain after and before spans at the both edges Contract.ThrowIfFalse(textSpan.Contains(tokens[TriviaLocation.AfterBeginningOfSpan].Span) && textSpan.Contains(tokens[TriviaLocation.BeforeEndOfSpan].Span)); var triviaList = GetTriviaAtEdges(tokens, textSpan); var annotations = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount) .Cast<TriviaLocation>() .ToDictionary(location => location, _ => new SyntaxAnnotation()); var map = CreateOldToNewTokensMap(tokens, annotations); var rootWithAnnotation = ReplaceTokens(root, map.Keys, (o, n) => map[o]); return CreateResult(rootWithAnnotation, annotations, triviaList); } private static SyntaxNode ReplaceTokens( SyntaxNode root, IEnumerable<SyntaxToken> oldTokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(oldTokens); Contract.ThrowIfNull(computeReplacementToken); return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n)); } private ITriviaSavedResult CreateResult( SyntaxNode root, Dictionary<TriviaLocation, SyntaxAnnotation> annotations, Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList) { return new Result(root, _endOfLineKind, annotations, triviaList); } private static Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, SyntaxToken> tokens, Dictionary<TriviaLocation, SyntaxAnnotation> annotations) { var token = default(SyntaxToken); var map = new Dictionary<SyntaxToken, SyntaxToken>(); var emptyList = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(); token = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => tokens[TriviaLocation.BeforeBeginningOfSpan]); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => tokens[TriviaLocation.AfterBeginningOfSpan]); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => tokens[TriviaLocation.BeforeEndOfSpan]); map[tokens[TriviaLocation.BeforeEndOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeEndOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => tokens[TriviaLocation.AfterEndOfSpan]); map[tokens[TriviaLocation.AfterEndOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterEndOfSpan]); return map; } private static Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> GetTriviaAtEdges(Dictionary<TriviaLocation, SyntaxToken> tokens, TextSpan textSpan) { var triviaAtBeginning = SplitTrivia(tokens[TriviaLocation.BeforeBeginningOfSpan], tokens[TriviaLocation.AfterBeginningOfSpan], t => t.FullSpan.End <= textSpan.Start); var triviaAtEnd = SplitTrivia(tokens[TriviaLocation.BeforeEndOfSpan], tokens[TriviaLocation.AfterEndOfSpan], t => t.FullSpan.Start < textSpan.End); var triviaList = new Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> { [TriviaLocation.BeforeBeginningOfSpan] = triviaAtBeginning.Item1, [TriviaLocation.AfterBeginningOfSpan] = triviaAtBeginning.Item2, [TriviaLocation.BeforeEndOfSpan] = triviaAtEnd.Item1, [TriviaLocation.AfterEndOfSpan] = triviaAtEnd.Item2 }; return triviaList; } private Dictionary<TriviaLocation, SyntaxToken> GetTokensAtEdges(SyntaxNode root, TextSpan textSpan) { var tokens = new Dictionary<TriviaLocation, SyntaxToken>(); tokens[TriviaLocation.AfterBeginningOfSpan] = _syntaxFacts.FindTokenOnRightOfPosition(root, textSpan.Start, includeSkipped: false); tokens[TriviaLocation.BeforeBeginningOfSpan] = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true); tokens[TriviaLocation.BeforeEndOfSpan] = _syntaxFacts.FindTokenOnLeftOfPosition(root, textSpan.End, includeSkipped: false); tokens[TriviaLocation.AfterEndOfSpan] = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true); return tokens; } private static Tuple<List<SyntaxTrivia>, List<SyntaxTrivia>> SplitTrivia( SyntaxToken token1, SyntaxToken token2, Func<SyntaxTrivia, bool> conditionToLeftAtCallSite) { var triviaLeftAtCallSite = new List<SyntaxTrivia>(); var triviaMovedToDefinition = new List<SyntaxTrivia>(); foreach (var trivia in token1.TrailingTrivia.Concat(token2.LeadingTrivia)) { if (conditionToLeftAtCallSite(trivia)) { triviaLeftAtCallSite.Add(trivia); } else { triviaMovedToDefinition.Add(trivia); } } return Tuple.Create(triviaLeftAtCallSite, triviaMovedToDefinition); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class AbstractSyntaxTriviaService : ISyntaxTriviaService { private const int TriviaLocationsCount = 4; private readonly ISyntaxFacts _syntaxFacts; private readonly int _endOfLineKind; protected AbstractSyntaxTriviaService(ISyntaxFacts syntaxFacts, int endOfLineKind) { _syntaxFacts = syntaxFacts; _endOfLineKind = endOfLineKind; } public ITriviaSavedResult SaveTriviaAroundSelection(SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); Debug.Assert(Enum.GetNames(typeof(TriviaLocation)).Length == TriviaLocationsCount); var tokens = GetTokensAtEdges(root, textSpan); // span must contain after and before spans at the both edges Contract.ThrowIfFalse(textSpan.Contains(tokens[TriviaLocation.AfterBeginningOfSpan].Span) && textSpan.Contains(tokens[TriviaLocation.BeforeEndOfSpan].Span)); var triviaList = GetTriviaAtEdges(tokens, textSpan); var annotations = Enumerable.Range((int)TriviaLocation.BeforeBeginningOfSpan, TriviaLocationsCount) .Cast<TriviaLocation>() .ToDictionary(location => location, _ => new SyntaxAnnotation()); var map = CreateOldToNewTokensMap(tokens, annotations); var rootWithAnnotation = ReplaceTokens(root, map.Keys, (o, n) => map[o]); return CreateResult(rootWithAnnotation, annotations, triviaList); } private static SyntaxNode ReplaceTokens( SyntaxNode root, IEnumerable<SyntaxToken> oldTokens, Func<SyntaxToken, SyntaxToken, SyntaxToken> computeReplacementToken) { Contract.ThrowIfNull(root); Contract.ThrowIfNull(oldTokens); Contract.ThrowIfNull(computeReplacementToken); return root.ReplaceTokens(oldTokens, (o, n) => computeReplacementToken(o, n)); } private ITriviaSavedResult CreateResult( SyntaxNode root, Dictionary<TriviaLocation, SyntaxAnnotation> annotations, Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> triviaList) { return new Result(root, _endOfLineKind, annotations, triviaList); } private static Dictionary<SyntaxToken, SyntaxToken> CreateOldToNewTokensMap( Dictionary<TriviaLocation, SyntaxToken> tokens, Dictionary<TriviaLocation, SyntaxAnnotation> annotations) { var token = default(SyntaxToken); var map = new Dictionary<SyntaxToken, SyntaxToken>(); var emptyList = SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(); token = map.GetOrAdd(tokens[TriviaLocation.BeforeBeginningOfSpan], _ => tokens[TriviaLocation.BeforeBeginningOfSpan]); map[tokens[TriviaLocation.BeforeBeginningOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterBeginningOfSpan], _ => tokens[TriviaLocation.AfterBeginningOfSpan]); map[tokens[TriviaLocation.AfterBeginningOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterBeginningOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.BeforeEndOfSpan], _ => tokens[TriviaLocation.BeforeEndOfSpan]); map[tokens[TriviaLocation.BeforeEndOfSpan]] = token.WithTrailingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.BeforeEndOfSpan]); token = map.GetOrAdd(tokens[TriviaLocation.AfterEndOfSpan], _ => tokens[TriviaLocation.AfterEndOfSpan]); map[tokens[TriviaLocation.AfterEndOfSpan]] = token.WithLeadingTrivia(emptyList).WithAdditionalAnnotations(annotations[TriviaLocation.AfterEndOfSpan]); return map; } private static Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> GetTriviaAtEdges(Dictionary<TriviaLocation, SyntaxToken> tokens, TextSpan textSpan) { var triviaAtBeginning = SplitTrivia(tokens[TriviaLocation.BeforeBeginningOfSpan], tokens[TriviaLocation.AfterBeginningOfSpan], t => t.FullSpan.End <= textSpan.Start); var triviaAtEnd = SplitTrivia(tokens[TriviaLocation.BeforeEndOfSpan], tokens[TriviaLocation.AfterEndOfSpan], t => t.FullSpan.Start < textSpan.End); var triviaList = new Dictionary<TriviaLocation, IEnumerable<SyntaxTrivia>> { [TriviaLocation.BeforeBeginningOfSpan] = triviaAtBeginning.Item1, [TriviaLocation.AfterBeginningOfSpan] = triviaAtBeginning.Item2, [TriviaLocation.BeforeEndOfSpan] = triviaAtEnd.Item1, [TriviaLocation.AfterEndOfSpan] = triviaAtEnd.Item2 }; return triviaList; } private Dictionary<TriviaLocation, SyntaxToken> GetTokensAtEdges(SyntaxNode root, TextSpan textSpan) { var tokens = new Dictionary<TriviaLocation, SyntaxToken>(); tokens[TriviaLocation.AfterBeginningOfSpan] = _syntaxFacts.FindTokenOnRightOfPosition(root, textSpan.Start, includeSkipped: false); tokens[TriviaLocation.BeforeBeginningOfSpan] = tokens[TriviaLocation.AfterBeginningOfSpan].GetPreviousToken(includeZeroWidth: true); tokens[TriviaLocation.BeforeEndOfSpan] = _syntaxFacts.FindTokenOnLeftOfPosition(root, textSpan.End, includeSkipped: false); tokens[TriviaLocation.AfterEndOfSpan] = tokens[TriviaLocation.BeforeEndOfSpan].GetNextToken(includeZeroWidth: true); return tokens; } private static Tuple<List<SyntaxTrivia>, List<SyntaxTrivia>> SplitTrivia( SyntaxToken token1, SyntaxToken token2, Func<SyntaxTrivia, bool> conditionToLeftAtCallSite) { var triviaLeftAtCallSite = new List<SyntaxTrivia>(); var triviaMovedToDefinition = new List<SyntaxTrivia>(); foreach (var trivia in token1.TrailingTrivia.Concat(token2.LeadingTrivia)) { if (conditionToLeftAtCallSite(trivia)) { triviaLeftAtCallSite.Add(trivia); } else { triviaMovedToDefinition.Add(trivia); } } return Tuple.Create(triviaLeftAtCallSite, triviaMovedToDefinition); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/CompletionOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Completion { [ExportOptionProvider, Shared] internal class CompletionOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CompletionOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( CompletionOptions.HideAdvancedMembers, CompletionOptions.TriggerOnTyping, CompletionOptions.TriggerOnTypingLetters2, CompletionOptions.ShowCompletionItemFilters, CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, CompletionOptions.EnterKeyBehavior, CompletionOptions.SnippetsBehavior, CompletionOptions.ShowItemsFromUnimportedNamespaces, CompletionOptions.TriggerInArgumentLists, CompletionOptions.EnableArgumentCompletionSnippets); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Completion { [ExportOptionProvider, Shared] internal class CompletionOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CompletionOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( CompletionOptions.HideAdvancedMembers, CompletionOptions.TriggerOnTyping, CompletionOptions.TriggerOnTypingLetters2, CompletionOptions.ShowCompletionItemFilters, CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, CompletionOptions.EnterKeyBehavior, CompletionOptions.SnippetsBehavior, CompletionOptions.ShowItemsFromUnimportedNamespaces, CompletionOptions.TriggerInArgumentLists, CompletionOptions.EnableArgumentCompletionSnippets); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/Async/AsynchronousOperationBlocker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { public sealed class AsynchronousOperationBlocker : IDisposable { private readonly ManualResetEvent _waitHandle; private readonly object _lockObj; private bool _blocking; private bool _disposed; public AsynchronousOperationBlocker() { _waitHandle = new ManualResetEvent(false); _lockObj = new object(); _blocking = true; } public bool IsBlockingOperations { get { lock (_lockObj) { return _blocking; } } private set { lock (_lockObj) { if (_blocking == value) { return; } _blocking = value; if (!_disposed) { if (_blocking) { _waitHandle.Reset(); } else { _waitHandle.Set(); } } } } } public void BlockOperations() => this.IsBlockingOperations = true; public void UnblockOperations() => this.IsBlockingOperations = false; public bool WaitIfBlocked(TimeSpan timeout) { if (_disposed) { FailFast.Fail("Badness"); } return _waitHandle.WaitOne(timeout); } public void Dispose() { if (!_disposed) { _disposed = true; _waitHandle.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { public sealed class AsynchronousOperationBlocker : IDisposable { private readonly ManualResetEvent _waitHandle; private readonly object _lockObj; private bool _blocking; private bool _disposed; public AsynchronousOperationBlocker() { _waitHandle = new ManualResetEvent(false); _lockObj = new object(); _blocking = true; } public bool IsBlockingOperations { get { lock (_lockObj) { return _blocking; } } private set { lock (_lockObj) { if (_blocking == value) { return; } _blocking = value; if (!_disposed) { if (_blocking) { _waitHandle.Reset(); } else { _waitHandle.Set(); } } } } } public void BlockOperations() => this.IsBlockingOperations = true; public void UnblockOperations() => this.IsBlockingOperations = false; public bool WaitIfBlocked(TimeSpan timeout) { if (_disposed) { FailFast.Fail("Badness"); } return _waitHandle.WaitOne(timeout); } public void Dispose() { if (!_disposed) { _disposed = true; _waitHandle.Dispose(); } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Diagnostic/MetadataLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in metadata. /// </summary> internal sealed class MetadataLocation : Location, IEquatable<MetadataLocation?> { private readonly IModuleSymbolInternal _module; internal MetadataLocation(IModuleSymbolInternal module) { RoslynDebug.Assert(module != null); _module = module; } public override LocationKind Kind { get { return LocationKind.MetadataFile; } } internal override IModuleSymbolInternal MetadataModuleInternal { get { return _module; } } public override int GetHashCode() { return _module.GetHashCode(); } public override bool Equals(object? obj) { return Equals(obj as MetadataLocation); } public bool Equals(MetadataLocation? other) { return other is object && other._module == _module; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in metadata. /// </summary> internal sealed class MetadataLocation : Location, IEquatable<MetadataLocation?> { private readonly IModuleSymbolInternal _module; internal MetadataLocation(IModuleSymbolInternal module) { RoslynDebug.Assert(module != null); _module = module; } public override LocationKind Kind { get { return LocationKind.MetadataFile; } } internal override IModuleSymbolInternal MetadataModuleInternal { get { return _module; } } public override int GetHashCode() { return _module.GetHashCode(); } public override bool Equals(object? obj) { return Equals(obj as MetadataLocation); } public bool Equals(MetadataLocation? other) { return other is object && other._module == _module; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharp/Completion/FSharpFileSystemCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal class FSharpFileSystemCompletionHelper { private readonly FileSystemCompletionHelper _fileSystemCompletionHelper; public FSharpFileSystemCompletionHelper( FSharpGlyph folderGlyph, FSharpGlyph fileGlyph, ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, CompletionItemRules itemRules) { _fileSystemCompletionHelper = new FileSystemCompletionHelper( FSharpGlyphHelpers.ConvertTo(folderGlyph), FSharpGlyphHelpers.ConvertTo(fileGlyph), searchPaths, baseDirectoryOpt, allowableExtensions, itemRules); } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) { return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal class FSharpFileSystemCompletionHelper { private readonly FileSystemCompletionHelper _fileSystemCompletionHelper; public FSharpFileSystemCompletionHelper( FSharpGlyph folderGlyph, FSharpGlyph fileGlyph, ImmutableArray<string> searchPaths, string baseDirectoryOpt, ImmutableArray<string> allowableExtensions, CompletionItemRules itemRules) { _fileSystemCompletionHelper = new FileSystemCompletionHelper( FSharpGlyphHelpers.ConvertTo(folderGlyph), FSharpGlyphHelpers.ConvertTo(fileGlyph), searchPaths, baseDirectoryOpt, allowableExtensions, itemRules); } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) { return _fileSystemCompletionHelper.GetItemsAsync(directoryPath, cancellationToken); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Compilation/TestSyntaxTreeOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using static Microsoft.CodeAnalysis.AnalyzerConfig; namespace Roslyn.Utilities { public sealed class TestSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider { private readonly Dictionary<SyntaxTree, Dictionary<string, ReportDiagnostic>>? _options; private readonly Dictionary<SyntaxTree, GeneratedKind>? _isGenerated; private readonly Dictionary<string, ReportDiagnostic>? _globalOptions; public TestSyntaxTreeOptionsProvider( IEqualityComparer<string> comparer, (string? key, ReportDiagnostic diagnostic) globalOption, params (SyntaxTree, (string, ReportDiagnostic)[])[] options) { _options = options.ToDictionary( x => x.Item1, x => x.Item2.ToDictionary( x => x.Item1, x => x.Item2, comparer) ); if (globalOption.key is object) { _globalOptions = new Dictionary<string, ReportDiagnostic>(Section.PropertiesKeyComparer) { { globalOption.key, globalOption.diagnostic } }; } _isGenerated = null; } public TestSyntaxTreeOptionsProvider( params (SyntaxTree, (string, ReportDiagnostic)[])[] options) : this(CaseInsensitiveComparison.Comparer, globalOption: default, options) { } public TestSyntaxTreeOptionsProvider( (string, ReportDiagnostic) globalOption, params (SyntaxTree, (string, ReportDiagnostic)[])[] options) : this(CaseInsensitiveComparison.Comparer, globalOption: globalOption, options) { } public TestSyntaxTreeOptionsProvider( SyntaxTree tree, params (string, ReportDiagnostic)[] options) : this(globalOption: default, new[] { (tree, options) }) { } public TestSyntaxTreeOptionsProvider( params (SyntaxTree, GeneratedKind isGenerated)[] isGenerated ) { _options = null; _isGenerated = isGenerated.ToDictionary( x => x.Item1, x => x.isGenerated ); } public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) => _isGenerated != null && _isGenerated.TryGetValue(tree, out var kind) ? kind : GeneratedKind.Unknown; public override bool TryGetDiagnosticValue( SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { if (_options != null && _options.TryGetValue(tree, out var diags) && diags.TryGetValue(diagnosticId, out severity)) { return true; } severity = ReportDiagnostic.Default; return false; } public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { if (_globalOptions is object && _globalOptions.TryGetValue(diagnosticId, out severity)) { return true; } severity = ReportDiagnostic.Default; 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.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using static Microsoft.CodeAnalysis.AnalyzerConfig; namespace Roslyn.Utilities { public sealed class TestSyntaxTreeOptionsProvider : SyntaxTreeOptionsProvider { private readonly Dictionary<SyntaxTree, Dictionary<string, ReportDiagnostic>>? _options; private readonly Dictionary<SyntaxTree, GeneratedKind>? _isGenerated; private readonly Dictionary<string, ReportDiagnostic>? _globalOptions; public TestSyntaxTreeOptionsProvider( IEqualityComparer<string> comparer, (string? key, ReportDiagnostic diagnostic) globalOption, params (SyntaxTree, (string, ReportDiagnostic)[])[] options) { _options = options.ToDictionary( x => x.Item1, x => x.Item2.ToDictionary( x => x.Item1, x => x.Item2, comparer) ); if (globalOption.key is object) { _globalOptions = new Dictionary<string, ReportDiagnostic>(Section.PropertiesKeyComparer) { { globalOption.key, globalOption.diagnostic } }; } _isGenerated = null; } public TestSyntaxTreeOptionsProvider( params (SyntaxTree, (string, ReportDiagnostic)[])[] options) : this(CaseInsensitiveComparison.Comparer, globalOption: default, options) { } public TestSyntaxTreeOptionsProvider( (string, ReportDiagnostic) globalOption, params (SyntaxTree, (string, ReportDiagnostic)[])[] options) : this(CaseInsensitiveComparison.Comparer, globalOption: globalOption, options) { } public TestSyntaxTreeOptionsProvider( SyntaxTree tree, params (string, ReportDiagnostic)[] options) : this(globalOption: default, new[] { (tree, options) }) { } public TestSyntaxTreeOptionsProvider( params (SyntaxTree, GeneratedKind isGenerated)[] isGenerated ) { _options = null; _isGenerated = isGenerated.ToDictionary( x => x.Item1, x => x.isGenerated ); } public override GeneratedKind IsGenerated(SyntaxTree tree, CancellationToken cancellationToken) => _isGenerated != null && _isGenerated.TryGetValue(tree, out var kind) ? kind : GeneratedKind.Unknown; public override bool TryGetDiagnosticValue( SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { if (_options != null && _options.TryGetValue(tree, out var diags) && diags.TryGetValue(diagnosticId, out severity)) { return true; } severity = ReportDiagnostic.Default; return false; } public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity) { if (_globalOptions is object && _globalOptions.TryGetValue(diagnosticId, out severity)) { return true; } severity = ReportDiagnostic.Default; return false; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/VisualBasic/Analyzers/xlf/VisualBasicAnalyzersResources.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="../VisualBasicAnalyzersResources.resx"> <body> <trans-unit id="GetType_can_be_converted_to_NameOf"> <source>'GetType' can be converted to 'NameOf'</source> <target state="translated">'GetType' peut être converti en 'NameOf'</target> <note /> </trans-unit> <trans-unit id="If_statement_can_be_simplified"> <source>'If' statement can be simplified</source> <target state="translated">L'instruction 'If' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Imports_statement_is_unnecessary"> <source>Imports statement is unnecessary.</source> <target state="translated">L'instruction Imports n'est pas utile.</target> <note /> </trans-unit> <trans-unit id="Object_creation_can_be_simplified"> <source>Object creation can be simplified</source> <target state="translated">La création d’objets peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Remove_ByVal"> <source>'ByVal' keyword is unnecessary and can be removed.</source> <target state="translated">Le mot clé 'ByVal' est inutile et peut être supprimé.</target> <note>{locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_IsNot_Nothing_check"> <source>Use 'IsNot Nothing' check</source> <target state="translated">Utiliser la vérification 'IsNot Nothing'</target> <note /> </trans-unit> <trans-unit id="Use_IsNot_expression"> <source>Use 'IsNot' expression</source> <target state="translated">Utiliser l'expression 'IsNot'</target> <note>{locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_Is_Nothing_check"> <source>Use 'Is Nothing' check</source> <target state="translated">Utiliser la vérification 'Is Nothing'</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="../VisualBasicAnalyzersResources.resx"> <body> <trans-unit id="GetType_can_be_converted_to_NameOf"> <source>'GetType' can be converted to 'NameOf'</source> <target state="translated">'GetType' peut être converti en 'NameOf'</target> <note /> </trans-unit> <trans-unit id="If_statement_can_be_simplified"> <source>'If' statement can be simplified</source> <target state="translated">L'instruction 'If' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Imports_statement_is_unnecessary"> <source>Imports statement is unnecessary.</source> <target state="translated">L'instruction Imports n'est pas utile.</target> <note /> </trans-unit> <trans-unit id="Object_creation_can_be_simplified"> <source>Object creation can be simplified</source> <target state="translated">La création d’objets peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Remove_ByVal"> <source>'ByVal' keyword is unnecessary and can be removed.</source> <target state="translated">Le mot clé 'ByVal' est inutile et peut être supprimé.</target> <note>{locked: ByVal}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_IsNot_Nothing_check"> <source>Use 'IsNot Nothing' check</source> <target state="translated">Utiliser la vérification 'IsNot Nothing'</target> <note /> </trans-unit> <trans-unit id="Use_IsNot_expression"> <source>Use 'IsNot' expression</source> <target state="translated">Utiliser l'expression 'IsNot'</target> <note>{locked: IsNot}This is a Visual Basic keyword and should not be localized or have its casing changed</note> </trans-unit> <trans-unit id="Use_Is_Nothing_check"> <source>Use 'Is Nothing' check</source> <target state="translated">Utiliser la vérification 'Is Nothing'</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Text/xlf/TextEditorResources.zh-Hant.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="zh-Hant" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">此快照集未包含指定的位置。</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">此快照集未包含指定的範圍。</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer 不是從 ITextBuffer 所建立的 SourceTextContainer。</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="zh-Hant" original="../TextEditorResources.resx"> <body> <trans-unit id="The_snapshot_does_not_contain_the_specified_position"> <source>The snapshot does not contain the specified position.</source> <target state="translated">此快照集未包含指定的位置。</target> <note /> </trans-unit> <trans-unit id="The_snapshot_does_not_contain_the_specified_span"> <source>The snapshot does not contain the specified span.</source> <target state="translated">此快照集未包含指定的範圍。</target> <note /> </trans-unit> <trans-unit id="textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer"> <source>textContainer is not a SourceTextContainer that was created from an ITextBuffer.</source> <target state="translated">textContainer 不是從 ITextBuffer 所建立的 SourceTextContainer。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/ConstructorDeclarationStructureTests.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.MetadataAsSource Public Class ConstructorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SubNewStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ConstructorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C {|hint:{|textspan:Sub $$New() End Sub|}|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", "Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|textspan2:{|hint:{|textspan:<Goo> |}{|#0:Sub $$New()|} End Sub|#0}|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("textspan2", "#0", "<Goo> Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. {|#1:<Goo> |}{|#0:Sub $$New()|} End Sub|#0}|#1} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("#1", "#0", "<Goo> Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. {|#1:<Goo> |}{|#0:Public Sub $$New()|} End Sub|#0}|#1} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("#1", "#0", "<Goo> Public Sub New() " & VisualBasicOutliningHelpers.Ellipsis, 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.MetadataAsSource Public Class ConstructorDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of SubNewStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ConstructorDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C {|hint:{|textspan:Sub $$New() End Sub|}|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", "Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|textspan2:{|hint:{|textspan:<Goo> |}{|#0:Sub $$New()|} End Sub|#0}|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("textspan2", "#0", "<Goo> Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. {|#1:<Goo> |}{|#0:Sub $$New()|} End Sub|#0}|#1} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("#1", "#0", "<Goo> Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. {|#1:<Goo> |}{|#0:Public Sub $$New()|} End Sub|#0}|#1} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True), Region("#1", "#0", "<Goo> Public Sub New() " & VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// A Workspace specific to Visual Studio. /// </summary> public abstract class VisualStudioWorkspace : Workspace { private BackgroundCompiler? _backgroundCompiler; private readonly BackgroundParser _backgroundParser; static VisualStudioWorkspace() { WatsonReporter.InitializeFatalErrorHandlers(); } internal VisualStudioWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Host) { _backgroundCompiler = new BackgroundCompiler(this); var cacheService = Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested += OnCacheFlushRequested; } _backgroundParser = new BackgroundParser(this); _backgroundParser.Start(); } private void OnCacheFlushRequested(object sender, EventArgs e) { if (_backgroundCompiler != null) { _backgroundCompiler.Dispose(); _backgroundCompiler = null; // PartialSemanticsEnabled will now return false } // No longer need cache notifications var cacheService = Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested -= OnCacheFlushRequested; } } protected internal override bool PartialSemanticsEnabled { get { return _backgroundCompiler != null; } } protected override void OnDocumentTextChanged(Document document) => _backgroundParser.Parse(document); protected override void OnDocumentClosing(DocumentId documentId) => _backgroundParser.CancelParse(documentId); internal override bool IgnoreUnchangeableDocumentsWhenApplyingChanges => true; /// <summary> /// Returns the hierarchy for a given project. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> for the project.</param> /// <returns>The <see cref="IVsHierarchy"/>, or null if the project doesn't have one.</returns> public abstract IVsHierarchy? GetHierarchy(ProjectId projectId); internal abstract Guid GetProjectGuid(ProjectId projectId); public virtual string? GetFilePath(DocumentId documentId) => CurrentSolution.GetTextDocument(documentId)?.FilePath; /// <summary> /// Given a document id, opens an invisible editor for the document. /// </summary> /// <returns>A unique instance of IInvisibleEditor that must be disposed by the caller.</returns> internal abstract IInvisibleEditor OpenInvisibleEditor(DocumentId documentId); /// <summary> /// Returns the <see cref="EnvDTE.FileCodeModel"/> for a given document. /// </summary> public abstract EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId); internal abstract object? GetBrowseObject(SymbolListItem symbolListItem); public abstract bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken); public abstract bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken); public abstract void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols); /// <summary> /// Creates a <see cref="PortableExecutableReference" /> that correctly retrieves the Visual Studio context, /// such as documentation comments in the correct language. /// </summary> /// <param name="filePath">The file path of the assembly or module.</param> /// <param name="properties">The properties for the reference.</param> public PortableExecutableReference CreatePortableExecutableReference(string filePath, MetadataReferenceProperties properties) => this.Services.GetRequiredService<IMetadataService>().GetReference(filePath, properties); internal abstract string? TryGetRuleSetPathForProject(ProjectId projectId); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// A Workspace specific to Visual Studio. /// </summary> public abstract class VisualStudioWorkspace : Workspace { private BackgroundCompiler? _backgroundCompiler; private readonly BackgroundParser _backgroundParser; static VisualStudioWorkspace() { WatsonReporter.InitializeFatalErrorHandlers(); } internal VisualStudioWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Host) { _backgroundCompiler = new BackgroundCompiler(this); var cacheService = Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested += OnCacheFlushRequested; } _backgroundParser = new BackgroundParser(this); _backgroundParser.Start(); } private void OnCacheFlushRequested(object sender, EventArgs e) { if (_backgroundCompiler != null) { _backgroundCompiler.Dispose(); _backgroundCompiler = null; // PartialSemanticsEnabled will now return false } // No longer need cache notifications var cacheService = Services.GetService<IWorkspaceCacheService>(); if (cacheService != null) { cacheService.CacheFlushRequested -= OnCacheFlushRequested; } } protected internal override bool PartialSemanticsEnabled { get { return _backgroundCompiler != null; } } protected override void OnDocumentTextChanged(Document document) => _backgroundParser.Parse(document); protected override void OnDocumentClosing(DocumentId documentId) => _backgroundParser.CancelParse(documentId); internal override bool IgnoreUnchangeableDocumentsWhenApplyingChanges => true; /// <summary> /// Returns the hierarchy for a given project. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> for the project.</param> /// <returns>The <see cref="IVsHierarchy"/>, or null if the project doesn't have one.</returns> public abstract IVsHierarchy? GetHierarchy(ProjectId projectId); internal abstract Guid GetProjectGuid(ProjectId projectId); public virtual string? GetFilePath(DocumentId documentId) => CurrentSolution.GetTextDocument(documentId)?.FilePath; /// <summary> /// Given a document id, opens an invisible editor for the document. /// </summary> /// <returns>A unique instance of IInvisibleEditor that must be disposed by the caller.</returns> internal abstract IInvisibleEditor OpenInvisibleEditor(DocumentId documentId); /// <summary> /// Returns the <see cref="EnvDTE.FileCodeModel"/> for a given document. /// </summary> public abstract EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId); internal abstract object? GetBrowseObject(SymbolListItem symbolListItem); public abstract bool TryGoToDefinition(ISymbol symbol, Project project, CancellationToken cancellationToken); public abstract bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken); public abstract void DisplayReferencedSymbols(Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols); /// <summary> /// Creates a <see cref="PortableExecutableReference" /> that correctly retrieves the Visual Studio context, /// such as documentation comments in the correct language. /// </summary> /// <param name="filePath">The file path of the assembly or module.</param> /// <param name="properties">The properties for the reference.</param> public PortableExecutableReference CreatePortableExecutableReference(string filePath, MetadataReferenceProperties properties) => this.Services.GetRequiredService<IMetadataService>().GetReference(filePath, properties); internal abstract string? TryGetRuleSetPathForProject(ProjectId projectId); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Syntax/Parser/ParseAsyncTests.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 Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseAsyncTests Inherits BasicTestBase <Fact> Public Sub ParseAsyncModifier() Dim tree = ParseAndVerify(<![CDATA[ Imports Async = System.Threading.Tasks.Task Module Program Public Const Async As Integer = 0 Public Async <Async(Async)> Async Function M() As Async Dim l = Sub() Dim async As Async = Nothing End Sub Dim l2 = Async Sub() Dim async As Async = Nothing End Sub End Function End Module Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>) Assert.Equal(2, Aggregate t In tree.GetRoot().DescendantTokens Where t.Kind = SyntaxKind.AsyncKeyword Into Count()) Dim fields = tree.GetRoot().DescendantNodes.OfType(Of FieldDeclarationSyntax)().ToArray() Assert.Equal(2, Aggregate f In fields Where f.Declarators(0).Names(0).Identifier.ValueText = "Async" Into Count()) End Sub <Fact> Public Sub ParseAwaitExpressions() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() Await t1 WriteLine(Await t2) End Sub Sub M2() Await t1 WriteLine(Await t2) End Sub Async Function N() As Task(Of Integer) Await t1 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="206" end="208"/> <error id="32017" message="Comma, ')', or a valid expression continuation expected." start="234" end="236"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="398" end="400"/> <error id="30198" message="')' expected." start="424" end="424"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)() Assert.Equal(4, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAwaitExpressionsWithPrecedence() Dim tree = ParseAndVerify(<![CDATA[ Module Program Async Function M(a As Task(Of Integer), x As Task(Of Integer), y As Task(Of Integer), b As Task(Of Integer)) As Task(Of Integer) Return Await a * Await x ^ Await y + Await b End Function End Module]]>) Dim returnStatement = tree.GetRoot().DescendantNodes.OfType(Of ReturnStatementSyntax).Single() Dim expression = CType(returnStatement.Expression, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AddExpression, expression.Kind) Assert.Equal(SyntaxKind.MultiplyExpression, expression.Left.Kind) Dim left = CType(expression.Left, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AwaitExpression, left.Left.Kind) Assert.Equal(SyntaxKind.ExponentiateExpression, left.Right.Kind) Dim right = expression.Right Assert.Equal(SyntaxKind.AwaitExpression, right.Kind) End Sub <Fact> Public Sub ParseAwaitStatements() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() ' await 1 Await t1 End Sub Sub M2() ' await 2 Await t1 Dim lambda = Async Sub() If True Then Await t1 : Await t2 ' await 3 and 4 End Sub Async Function N() As Task(Of Integer) ' await 5 Await t1 ' await 6 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function Async Function N3(a, x, y) As Task ' This is a parse error, end of statement expected after 'Await a' Await a * Await x * Await y End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="177" end="179"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="407" end="409"/> <error id="30198" message="')' expected." start="433" end="433"/> <error id="30205" message="End of statement expected." start="588" end="589"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)().ToArray() Assert.Equal(6, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAsyncLambdas() Dim tree = ParseAndVerify(<![CDATA[ Module Program Private t1 As Task Private t2 As Task(Of Integer) Private f As Integer Sub Main() ' Statement Dim slAsyncSub1 = Async Sub() Await t1 ' Assignment Dim slAsyncSub2 = Async Sub() f = Await t2 ' Expression Dim slAsyncFunction1 = Async Function() Await t2 ' Comparison Dim slAsyncFunction2 = Async Function() f = Await t2 Dim mlAsyncSub = Async Sub() Await t1 End Sub Dim mlAsyncFunction1 = Async Function() Await t1 End Function Dim mlAsyncFunction2 = Async Function() Await t1 Return Await t2 End Function End Sub End Module]]>) Dim lambdas = tree.GetRoot().DescendantNodes.OfType(Of LambdaExpressionSyntax)().ToArray() Assert.Equal(7, lambdas.Count) Assert.Equal(4, lambdas.Count(Function(l) SyntaxFacts.IsSingleLineLambdaExpression(l.Kind))) Assert.Equal(SyntaxKind.ExpressionStatement, CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body, ExpressionStatementSyntax).Expression.Kind) Assert.Equal(SyntaxKind.SimpleAssignmentStatement, CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body, AssignmentStatementSyntax).Right.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(lambdas(2), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.EqualsExpression, CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body, BinaryExpressionSyntax).Right.Kind) Assert.Equal(3, lambdas.Count(Function(l) SyntaxFacts.IsMultiLineLambdaExpression(l.Kind))) End Sub <Fact> Public Sub ParseAsyncWithNesting() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Imports Async = System.Threading.Tasks.Task Class C Public Const Async As Integer = 0 <Async(Async)> Async Function M() As Async Dim t As Task Await (t) ' Yes Dim lambda1 = Function() Await (t) ' No Dim lambda1a = Sub() Await (t) ' No Dim lambda1b = Async Function() Await t ' Yes Dim lambda1c = Async Function() Await (Sub() Await (Function() Await (Function() (Function() Async Sub() Await t)())()) End Sub) ' Yes, No, No, Yes Return Await t ' Yes End Function [Await] t ' No End Function Sub Await(Optional p = Nothing) Dim t As Task Await (t) ' No Dim lambda1 = Async Function() Await (t) ' Yes Dim lambda1a = Async Sub() Await (t) ' Yes Dim lambda1b = Function() Await (t) ' No Dim lambda1c = Function() Await (Async Sub() Await (Async Function() Await (Async Function() (Function() Sub() Await t)())()) End Sub) ' No, Yes, Yes, No Return Await (t) ' No End Function Await t End Sub Function Await(t) Return Nothing End Function End Class Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>.Value) ' Error BC30800: Method arguments must be enclosed in parentheses. Assert.True(Aggregate d In tree.GetDiagnostics() Into All(d.Code = ERRID.ERR_ObsoleteArgumentsNeedParens)) Dim asyncExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim invocationExpression = tree.GetRoot().DescendantNodes.OfType(Of InvocationExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim allParsedExpressions = tree.GetRoot().DescendantNodes.OfType(Of ExpressionSyntax)() Dim parsedExpressions = From expression In allParsedExpressions Where expression.Kind = SyntaxKind.AwaitExpression OrElse (expression.Kind = SyntaxKind.IdentifierName AndAlso DirectCast(expression, IdentifierNameSyntax).Identifier.ValueText.Equals("Await")) Order By expression.Position Select expression.Kind Dim expected = {SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName} Assert.Equal(expected, parsedExpressions) End Sub <Fact> Public Sub ParseAwaitInScriptingAndInteractive() Dim source = " Dim i = Await T + Await(T) ' Yes, Yes Dim l = Sub() Await T ' No End Sub Function M() Return Await T ' No End Function Async Sub N() Await T ' Yes Await(T) ' Yes End Sub Async Function F() Return Await(T) ' Yes End Function" Dim tree = VisualBasicSyntaxTree.ParseText(source, options:=TestOptions.Script) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(5, awaitExpressions.Count) Dim awaitParsedAsIdentifier = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText.Equals("Await")).ToArray() Assert.Equal(2, awaitParsedAsIdentifier.Count) End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Public Class ParseAsyncTests Inherits BasicTestBase <Fact> Public Sub ParseAsyncModifier() Dim tree = ParseAndVerify(<![CDATA[ Imports Async = System.Threading.Tasks.Task Module Program Public Const Async As Integer = 0 Public Async <Async(Async)> Async Function M() As Async Dim l = Sub() Dim async As Async = Nothing End Sub Dim l2 = Async Sub() Dim async As Async = Nothing End Sub End Function End Module Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>) Assert.Equal(2, Aggregate t In tree.GetRoot().DescendantTokens Where t.Kind = SyntaxKind.AsyncKeyword Into Count()) Dim fields = tree.GetRoot().DescendantNodes.OfType(Of FieldDeclarationSyntax)().ToArray() Assert.Equal(2, Aggregate f In fields Where f.Declarators(0).Names(0).Identifier.ValueText = "Async" Into Count()) End Sub <Fact> Public Sub ParseAwaitExpressions() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() Await t1 WriteLine(Await t2) End Sub Sub M2() Await t1 WriteLine(Await t2) End Sub Async Function N() As Task(Of Integer) Await t1 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="206" end="208"/> <error id="32017" message="Comma, ')', or a valid expression continuation expected." start="234" end="236"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="398" end="400"/> <error id="30198" message="')' expected." start="424" end="424"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)() Assert.Equal(4, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAwaitExpressionsWithPrecedence() Dim tree = ParseAndVerify(<![CDATA[ Module Program Async Function M(a As Task(Of Integer), x As Task(Of Integer), y As Task(Of Integer), b As Task(Of Integer)) As Task(Of Integer) Return Await a * Await x ^ Await y + Await b End Function End Module]]>) Dim returnStatement = tree.GetRoot().DescendantNodes.OfType(Of ReturnStatementSyntax).Single() Dim expression = CType(returnStatement.Expression, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AddExpression, expression.Kind) Assert.Equal(SyntaxKind.MultiplyExpression, expression.Left.Kind) Dim left = CType(expression.Left, BinaryExpressionSyntax) Assert.Equal(SyntaxKind.AwaitExpression, left.Left.Kind) Assert.Equal(SyntaxKind.ExponentiateExpression, left.Right.Kind) Dim right = expression.Right Assert.Equal(SyntaxKind.AwaitExpression, right.Kind) End Sub <Fact> Public Sub ParseAwaitStatements() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Console Module Program Private t1 As Task Private t2 As Task(Of Integer) Async Sub M() ' await 1 Await t1 End Sub Sub M2() ' await 2 Await t1 Dim lambda = Async Sub() If True Then Await t1 : Await t2 ' await 3 and 4 End Sub Async Function N() As Task(Of Integer) ' await 5 Await t1 ' await 6 Return Await t2 End Function Function N2() Await t1 Return (Await t2) End Function Async Function N3(a, x, y) As Task ' This is a parse error, end of statement expected after 'Await a' Await a * Await x * Await y End Function End Module]]>, <errors> <error id="30800" message="Method arguments must be enclosed in parentheses." start="177" end="179"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="407" end="409"/> <error id="30198" message="')' expected." start="433" end="433"/> <error id="30205" message="End of statement expected." start="588" end="589"/> </errors>) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax)().ToArray() Assert.Equal(6, awaitExpressions.Count) Dim firstStatementOfM = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax).First.Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfM2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(1).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(2).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(firstStatementOfM, ExpressionStatementSyntax).Expression.Kind) Dim firstStatementOfN2 = tree.GetRoot().DescendantNodes.OfType(Of MethodBlockBaseSyntax)()(3).Statements.First Assert.Equal(SyntaxKind.ExpressionStatement, firstStatementOfM2.Kind) Assert.Equal(SyntaxKind.InvocationExpression, CType(firstStatementOfM2, ExpressionStatementSyntax).Expression.Kind) End Sub <Fact> Public Sub ParseAsyncLambdas() Dim tree = ParseAndVerify(<![CDATA[ Module Program Private t1 As Task Private t2 As Task(Of Integer) Private f As Integer Sub Main() ' Statement Dim slAsyncSub1 = Async Sub() Await t1 ' Assignment Dim slAsyncSub2 = Async Sub() f = Await t2 ' Expression Dim slAsyncFunction1 = Async Function() Await t2 ' Comparison Dim slAsyncFunction2 = Async Function() f = Await t2 Dim mlAsyncSub = Async Sub() Await t1 End Sub Dim mlAsyncFunction1 = Async Function() Await t1 End Function Dim mlAsyncFunction2 = Async Function() Await t1 Return Await t2 End Function End Sub End Module]]>) Dim lambdas = tree.GetRoot().DescendantNodes.OfType(Of LambdaExpressionSyntax)().ToArray() Assert.Equal(7, lambdas.Count) Assert.Equal(4, lambdas.Count(Function(l) SyntaxFacts.IsSingleLineLambdaExpression(l.Kind))) Assert.Equal(SyntaxKind.ExpressionStatement, CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(0), SingleLineLambdaExpressionSyntax).Body, ExpressionStatementSyntax).Expression.Kind) Assert.Equal(SyntaxKind.SimpleAssignmentStatement, CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(1), SingleLineLambdaExpressionSyntax).Body, AssignmentStatementSyntax).Right.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(lambdas(2), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.EqualsExpression, CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body.Kind) Assert.Equal(SyntaxKind.AwaitExpression, CType(CType(lambdas(3), SingleLineLambdaExpressionSyntax).Body, BinaryExpressionSyntax).Right.Kind) Assert.Equal(3, lambdas.Count(Function(l) SyntaxFacts.IsMultiLineLambdaExpression(l.Kind))) End Sub <Fact> Public Sub ParseAsyncWithNesting() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Imports Async = System.Threading.Tasks.Task Class C Public Const Async As Integer = 0 <Async(Async)> Async Function M() As Async Dim t As Task Await (t) ' Yes Dim lambda1 = Function() Await (t) ' No Dim lambda1a = Sub() Await (t) ' No Dim lambda1b = Async Function() Await t ' Yes Dim lambda1c = Async Function() Await (Sub() Await (Function() Await (Function() (Function() Async Sub() Await t)())()) End Sub) ' Yes, No, No, Yes Return Await t ' Yes End Function [Await] t ' No End Function Sub Await(Optional p = Nothing) Dim t As Task Await (t) ' No Dim lambda1 = Async Function() Await (t) ' Yes Dim lambda1a = Async Sub() Await (t) ' Yes Dim lambda1b = Function() Await (t) ' No Dim lambda1c = Function() Await (Async Sub() Await (Async Function() Await (Async Function() (Function() Sub() Await t)())()) End Sub) ' No, Yes, Yes, No Return Await (t) ' No End Function Await t End Sub Function Await(t) Return Nothing End Function End Class Class AsyncAttribute Inherits Attribute Sub New(p) End Sub End Class]]>.Value) ' Error BC30800: Method arguments must be enclosed in parentheses. Assert.True(Aggregate d In tree.GetDiagnostics() Into All(d.Code = ERRID.ERR_ObsoleteArgumentsNeedParens)) Dim asyncExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim invocationExpression = tree.GetRoot().DescendantNodes.OfType(Of InvocationExpressionSyntax).ToArray() Assert.Equal(9, asyncExpressions.Count) Dim allParsedExpressions = tree.GetRoot().DescendantNodes.OfType(Of ExpressionSyntax)() Dim parsedExpressions = From expression In allParsedExpressions Where expression.Kind = SyntaxKind.AwaitExpression OrElse (expression.Kind = SyntaxKind.IdentifierName AndAlso DirectCast(expression, IdentifierNameSyntax).Identifier.ValueText.Equals("Await")) Order By expression.Position Select expression.Kind Dim expected = {SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.AwaitExpression, SyntaxKind.AwaitExpression, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName, SyntaxKind.IdentifierName} Assert.Equal(expected, parsedExpressions) End Sub <Fact> Public Sub ParseAwaitInScriptingAndInteractive() Dim source = " Dim i = Await T + Await(T) ' Yes, Yes Dim l = Sub() Await T ' No End Sub Function M() Return Await T ' No End Function Async Sub N() Await T ' Yes Await(T) ' Yes End Sub Async Function F() Return Await(T) ' Yes End Function" Dim tree = VisualBasicSyntaxTree.ParseText(source, options:=TestOptions.Script) Dim awaitExpressions = tree.GetRoot().DescendantNodes.OfType(Of AwaitExpressionSyntax).ToArray() Assert.Equal(5, awaitExpressions.Count) Dim awaitParsedAsIdentifier = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText.Equals("Await")).ToArray() Assert.Equal(2, awaitParsedAsIdentifier.Count) End Sub End Class
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/LanguageServer/ProtocolUnitTests/Hover/HoverTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Hover { public class HoverTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetHoverAsync() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <param name='i'>an int</param> /// <returns>a string</returns> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, $"string A.Method(int i)|A great method|{FeaturesResources.Returns_colon}| |a string"); } [Fact] public async Task TestGetHoverAsync_WithExceptions() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, $"string A.Method(int i)|A great method|{FeaturesResources.Exceptions_colon}| System.NullReferenceException"); } [Fact] public async Task TestGetHoverAsync_WithRemarks() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <remarks> /// Remarks are cool too. /// </remarks> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, "string A.Method(int i)|A great method|Remarks are cool too."); } [Fact] public async Task TestGetHoverAsync_WithList() { var markup = @"class A { /// <summary> /// A great method /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// </summary> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, "string A.Method(int i)|A great method|• |Item 1.|• |Item 2."); } [Fact] public async Task TestGetHoverAsync_InvalidLocation() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <param name='i'>an int</param> /// <returns>a string</returns> private string Method(int i) { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetHoverAsync(testLspServer, locations["caret"].Single()).ConfigureAwait(false); Assert.Null(results); } // Test that if we pass a project context along to hover, the right context is chosen. We are using hover // as a general proxy to test that our context tracking works in all cases, although there's nothing specific // about hover that needs to be different here compared to any other feature. [Fact] public async Task TestGetHoverWithProjectContexts() { var source = @" using System; #if NET472 class WithConstant { public const string Target = ""Target in net472""; } #else class WithConstant { public const string Target = ""Target in netcoreapp3.1""; } #endif class Program { static void Main(string[] args) { Console.WriteLine(WithConstant.{|caret:Target|}); } }"; var workspaceXml = $@"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Net472"" PreprocessorSymbols=""NET472""> <Document FilePath=""C:\C.cs""><![CDATA[${source}]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""NetCoreApp3"" PreprocessorSymbols=""NETCOREAPP3.1""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""Net472""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var location = locations["caret"].Single(); foreach (var project in testLspServer.GetCurrentSolution().Projects) { var result = await RunGetHoverAsync(testLspServer, location, project.Id); var expectedConstant = project.Name == "Net472" ? "Target in net472" : "Target in netcoreapp3.1"; VerifyVSContent(result, $"({FeaturesResources.constant}) string WithConstant.Target = \"{expectedConstant}\""); } } [Fact] public async Task TestGetHoverAsync_UsingMarkupContent() { var markup = @"class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> /// <param name='i'>an int</param> /// <returns>a string</returns> /// <remarks> /// Remarks are cool too. /// </remarks> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedMarkdown = @$"```csharp void A.AMethod(int i) ``` A&nbsp;cref&nbsp;A\.AMethod\(int\) **strong&nbsp;text** _italic&nbsp;text_ <u>underline&nbsp;text</u> •&nbsp;Item&nbsp;1\. •&nbsp;Item&nbsp;2\. [link text](https://google.com) Remarks&nbsp;are&nbsp;cool&nbsp;too\. {FeaturesResources.Returns_colon} &nbsp;&nbsp;a&nbsp;string {FeaturesResources.Exceptions_colon} &nbsp;&nbsp;System\.NullReferenceException "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities { TextDocument = new LSP.TextDocumentClientCapabilities { Hover = new LSP.HoverSetting { ContentFormat = new LSP.MarkupKind[] { LSP.MarkupKind.Markdown } } } }).ConfigureAwait(false); Assert.Equal(expectedMarkdown, results.Contents.Third.Value); } [Fact] public async Task TestGetHoverAsync_WithoutMarkdownClientSupport() { var markup = @"class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> /// <param name='i'>an int</param> /// <returns>a string</returns> /// <remarks> /// Remarks are cool too. /// </remarks> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedText = @$"void A.AMethod(int i) A cref A.AMethod(int) strong text italic text underline text • Item 1. • Item 2. link text Remarks are cool too. {FeaturesResources.Returns_colon} a string {FeaturesResources.Exceptions_colon} System.NullReferenceException "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities()).ConfigureAwait(false); Assert.Equal(expectedText, results.Contents.Third.Value); } [Fact] public async Task TestGetHoverAsync_UsingMarkupContentProperlyEscapes() { var markup = @"class A { /// <summary> /// Some {curly} [braces] and (parens) /// <br/> /// #Hashtag /// <br/> /// 1 + 1 - 1 /// <br/> /// Period. /// <br/> /// Exclaim! /// <br/> /// <strong>strong\** text</strong> /// <br/> /// <em>italic_ **text**</em> /// <br/> /// <a href = ""https://google.com""> closing] link</a> /// </summary> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedMarkdown = @"```csharp void A.AMethod(int i) ``` Some&nbsp;\{curly\}&nbsp;\[braces\]&nbsp;and&nbsp;\(parens\) \#Hashtag 1&nbsp;\+&nbsp;1&nbsp;\-&nbsp;1 Period\. Exclaim\! **strong\\\*\*&nbsp;text** _italic\_&nbsp;\*\*text\*\*_ [closing\] link](https://google.com) "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities { TextDocument = new LSP.TextDocumentClientCapabilities { Hover = new LSP.HoverSetting { ContentFormat = new LSP.MarkupKind[] { LSP.MarkupKind.Markdown } } } }).ConfigureAwait(false); Assert.Equal(expectedMarkdown, results.Contents.Third.Value); } private static async Task<LSP.Hover> RunGetHoverAsync( TestLspServer testLspServer, LSP.Location caret, ProjectId projectContext = null, LSP.ClientCapabilities clientCapabilities = null) { clientCapabilities ??= new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true }; return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Hover>(LSP.Methods.TextDocumentHoverName, CreateTextDocumentPositionParams(caret, projectContext), clientCapabilities, null, CancellationToken.None); } private void VerifyVSContent(LSP.Hover hover, string expectedContent) { var vsHover = Assert.IsType<LSP.VSHover>(hover); var containerElement = (ContainerElement)vsHover.RawContent; using var _ = ArrayBuilder<ClassifiedTextElement>.GetInstance(out var classifiedTextElements); GetClassifiedTextElements(containerElement, classifiedTextElements); Assert.False(classifiedTextElements.SelectMany(classifiedTextElements => classifiedTextElements.Runs).Any(run => run.NavigationAction != null)); var content = string.Join("|", classifiedTextElements.Select(cte => string.Join(string.Empty, cte.Runs.Select(ctr => ctr.Text)))); Assert.Equal(expectedContent, content); } private void GetClassifiedTextElements(ContainerElement container, ArrayBuilder<ClassifiedTextElement> classifiedTextElements) { foreach (var element in container.Elements) { if (element is ClassifiedTextElement classifiedTextElement) { classifiedTextElements.Add(classifiedTextElement); } else if (element is ContainerElement containerElement) { GetClassifiedTextElements(containerElement, classifiedTextElements); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Hover { public class HoverTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetHoverAsync() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <param name='i'>an int</param> /// <returns>a string</returns> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, $"string A.Method(int i)|A great method|{FeaturesResources.Returns_colon}| |a string"); } [Fact] public async Task TestGetHoverAsync_WithExceptions() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, $"string A.Method(int i)|A great method|{FeaturesResources.Exceptions_colon}| System.NullReferenceException"); } [Fact] public async Task TestGetHoverAsync_WithRemarks() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <remarks> /// Remarks are cool too. /// </remarks> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, "string A.Method(int i)|A great method|Remarks are cool too."); } [Fact] public async Task TestGetHoverAsync_WithList() { var markup = @"class A { /// <summary> /// A great method /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// </summary> private string {|caret:Method|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var results = await RunGetHoverAsync(testLspServer, expectedLocation).ConfigureAwait(false); VerifyVSContent(results, "string A.Method(int i)|A great method|• |Item 1.|• |Item 2."); } [Fact] public async Task TestGetHoverAsync_InvalidLocation() { var markup = @"class A { /// <summary> /// A great method /// </summary> /// <param name='i'>an int</param> /// <returns>a string</returns> private string Method(int i) { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGetHoverAsync(testLspServer, locations["caret"].Single()).ConfigureAwait(false); Assert.Null(results); } // Test that if we pass a project context along to hover, the right context is chosen. We are using hover // as a general proxy to test that our context tracking works in all cases, although there's nothing specific // about hover that needs to be different here compared to any other feature. [Fact] public async Task TestGetHoverWithProjectContexts() { var source = @" using System; #if NET472 class WithConstant { public const string Target = ""Target in net472""; } #else class WithConstant { public const string Target = ""Target in netcoreapp3.1""; } #endif class Program { static void Main(string[] args) { Console.WriteLine(WithConstant.{|caret:Target|}); } }"; var workspaceXml = $@"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Net472"" PreprocessorSymbols=""NET472""> <Document FilePath=""C:\C.cs""><![CDATA[${source}]]></Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""NetCoreApp3"" PreprocessorSymbols=""NETCOREAPP3.1""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""Net472""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var location = locations["caret"].Single(); foreach (var project in testLspServer.GetCurrentSolution().Projects) { var result = await RunGetHoverAsync(testLspServer, location, project.Id); var expectedConstant = project.Name == "Net472" ? "Target in net472" : "Target in netcoreapp3.1"; VerifyVSContent(result, $"({FeaturesResources.constant}) string WithConstant.Target = \"{expectedConstant}\""); } } [Fact] public async Task TestGetHoverAsync_UsingMarkupContent() { var markup = @"class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> /// <param name='i'>an int</param> /// <returns>a string</returns> /// <remarks> /// Remarks are cool too. /// </remarks> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedMarkdown = @$"```csharp void A.AMethod(int i) ``` A&nbsp;cref&nbsp;A\.AMethod\(int\) **strong&nbsp;text** _italic&nbsp;text_ <u>underline&nbsp;text</u> •&nbsp;Item&nbsp;1\. •&nbsp;Item&nbsp;2\. [link text](https://google.com) Remarks&nbsp;are&nbsp;cool&nbsp;too\. {FeaturesResources.Returns_colon} &nbsp;&nbsp;a&nbsp;string {FeaturesResources.Exceptions_colon} &nbsp;&nbsp;System\.NullReferenceException "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities { TextDocument = new LSP.TextDocumentClientCapabilities { Hover = new LSP.HoverSetting { ContentFormat = new LSP.MarkupKind[] { LSP.MarkupKind.Markdown } } } }).ConfigureAwait(false); Assert.Equal(expectedMarkdown, results.Contents.Third.Value); } [Fact] public async Task TestGetHoverAsync_WithoutMarkdownClientSupport() { var markup = @"class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> /// <exception cref='System.NullReferenceException'> /// Oh no! /// </exception> /// <param name='i'>an int</param> /// <returns>a string</returns> /// <remarks> /// Remarks are cool too. /// </remarks> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedText = @$"void A.AMethod(int i) A cref A.AMethod(int) strong text italic text underline text • Item 1. • Item 2. link text Remarks are cool too. {FeaturesResources.Returns_colon} a string {FeaturesResources.Exceptions_colon} System.NullReferenceException "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities()).ConfigureAwait(false); Assert.Equal(expectedText, results.Contents.Third.Value); } [Fact] public async Task TestGetHoverAsync_UsingMarkupContentProperlyEscapes() { var markup = @"class A { /// <summary> /// Some {curly} [braces] and (parens) /// <br/> /// #Hashtag /// <br/> /// 1 + 1 - 1 /// <br/> /// Period. /// <br/> /// Exclaim! /// <br/> /// <strong>strong\** text</strong> /// <br/> /// <em>italic_ **text**</em> /// <br/> /// <a href = ""https://google.com""> closing] link</a> /// </summary> void {|caret:AMethod|}(int i) { } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var expectedLocation = locations["caret"].Single(); var expectedMarkdown = @"```csharp void A.AMethod(int i) ``` Some&nbsp;\{curly\}&nbsp;\[braces\]&nbsp;and&nbsp;\(parens\) \#Hashtag 1&nbsp;\+&nbsp;1&nbsp;\-&nbsp;1 Period\. Exclaim\! **strong\\\*\*&nbsp;text** _italic\_&nbsp;\*\*text\*\*_ [closing\] link](https://google.com) "; var results = await RunGetHoverAsync( testLspServer, expectedLocation, clientCapabilities: new LSP.ClientCapabilities { TextDocument = new LSP.TextDocumentClientCapabilities { Hover = new LSP.HoverSetting { ContentFormat = new LSP.MarkupKind[] { LSP.MarkupKind.Markdown } } } }).ConfigureAwait(false); Assert.Equal(expectedMarkdown, results.Contents.Third.Value); } private static async Task<LSP.Hover> RunGetHoverAsync( TestLspServer testLspServer, LSP.Location caret, ProjectId projectContext = null, LSP.ClientCapabilities clientCapabilities = null) { clientCapabilities ??= new LSP.VSClientCapabilities { SupportsVisualStudioExtensions = true }; return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Hover>(LSP.Methods.TextDocumentHoverName, CreateTextDocumentPositionParams(caret, projectContext), clientCapabilities, null, CancellationToken.None); } private void VerifyVSContent(LSP.Hover hover, string expectedContent) { var vsHover = Assert.IsType<LSP.VSHover>(hover); var containerElement = (ContainerElement)vsHover.RawContent; using var _ = ArrayBuilder<ClassifiedTextElement>.GetInstance(out var classifiedTextElements); GetClassifiedTextElements(containerElement, classifiedTextElements); Assert.False(classifiedTextElements.SelectMany(classifiedTextElements => classifiedTextElements.Runs).Any(run => run.NavigationAction != null)); var content = string.Join("|", classifiedTextElements.Select(cte => string.Join(string.Empty, cte.Runs.Select(ctr => ctr.Text)))); Assert.Equal(expectedContent, content); } private void GetClassifiedTextElements(ContainerElement container, ArrayBuilder<ClassifiedTextElement> classifiedTextElements) { foreach (var element in container.Elements) { if (element is ClassifiedTextElement classifiedTextElement) { classifiedTextElements.Add(classifiedTextElement); } else if (element is ContainerElement containerElement) { GetClassifiedTextElements(containerElement, classifiedTextElements); } } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveWorkspace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace : Workspace { private readonly ISolutionCrawlerRegistrationService _registrationService; private SourceTextContainer? _openTextContainer; private DocumentId? _openDocumentId; internal InteractiveWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Interactive) { // register work coordinator for this workspace _registrationService = Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator _registrationService.Unregister(this, blockingShutdown: true); base.Dispose(finalize); } public override bool CanOpenDocuments => true; public override bool CanApplyChange(ApplyChangesKind feature) => feature == ApplyChangesKind.ChangeDocument; public void OpenDocument(DocumentId documentId, SourceTextContainer textContainer) { _openTextContainer = textContainer; _openDocumentId = documentId; OnDocumentOpened(documentId, textContainer); } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { if (_openDocumentId != document) { return; } Contract.ThrowIfNull(_openTextContainer); ITextSnapshot appliedText; using (var edit = _openTextContainer.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { var oldText = _openTextContainer.CurrentText; var changes = newText.GetTextChanges(oldText); foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } appliedText = edit.Apply(); } OnDocumentTextChanged(document, appliedText.AsText(), PreservationMode.PreserveIdentity); } /// <summary> /// Closes all open documents and empties the solution but keeps all solution-level analyzers. /// </summary> public void ResetSolution() { ClearOpenDocuments(); var emptySolution = CreateSolution(SolutionId.CreateNewId("InteractiveSolution")); SetCurrentSolution(solution => emptySolution.WithAnalyzerReferences(solution.AnalyzerReferences), WorkspaceChangeKind.SolutionCleared); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace : Workspace { private readonly ISolutionCrawlerRegistrationService _registrationService; private SourceTextContainer? _openTextContainer; private DocumentId? _openDocumentId; internal InteractiveWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Interactive) { // register work coordinator for this workspace _registrationService = Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator _registrationService.Unregister(this, blockingShutdown: true); base.Dispose(finalize); } public override bool CanOpenDocuments => true; public override bool CanApplyChange(ApplyChangesKind feature) => feature == ApplyChangesKind.ChangeDocument; public void OpenDocument(DocumentId documentId, SourceTextContainer textContainer) { _openTextContainer = textContainer; _openDocumentId = documentId; OnDocumentOpened(documentId, textContainer); } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { if (_openDocumentId != document) { return; } Contract.ThrowIfNull(_openTextContainer); ITextSnapshot appliedText; using (var edit = _openTextContainer.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { var oldText = _openTextContainer.CurrentText; var changes = newText.GetTextChanges(oldText); foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } appliedText = edit.Apply(); } OnDocumentTextChanged(document, appliedText.AsText(), PreservationMode.PreserveIdentity); } /// <summary> /// Closes all open documents and empties the solution but keeps all solution-level analyzers. /// </summary> public void ResetSolution() { ClearOpenDocuments(); var emptySolution = CreateSolution(SolutionId.CreateNewId("InteractiveSolution")); SetCurrentSolution(solution => emptySolution.WithAnalyzerReferences(solution.AnalyzerReferences), WorkspaceChangeKind.SolutionCleared); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioTextUndoHistoryWorkspaceServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceServiceFactory(typeof(ITextUndoHistoryWorkspaceService), ServiceLayer.Host), Shared] internal class VisualStudioTextUndoHistoryWorkspaceServiceFactory : IWorkspaceServiceFactory { private readonly ITextUndoHistoryWorkspaceService _serviceSingleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextUndoHistoryWorkspaceServiceFactory(ITextUndoHistoryRegistry undoHistoryRegistry) => _serviceSingleton = new TextUndoHistoryWorkspaceService(undoHistoryRegistry); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _serviceSingleton; private class TextUndoHistoryWorkspaceService : ITextUndoHistoryWorkspaceService { private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; public TextUndoHistoryWorkspaceService(ITextUndoHistoryRegistry undoHistoryRegistry) => _undoHistoryRegistry = undoHistoryRegistry; public bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory) { switch (editorWorkspace) { case VisualStudioWorkspaceImpl visualStudioWorkspace: // TODO: Handle undo if context changes var documentId = editorWorkspace.GetDocumentIdInCurrentContext(textBuffer.AsTextContainer()); if (documentId == null) { undoHistory = null; return false; } // In the Visual Studio case, there might be projection buffers involved for Venus, // where we associate undo history with the surface buffer and not the subject buffer. var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument != null) { textBuffer = containedDocument.DataBuffer; } break; case MiscellaneousFilesWorkspace _: // Nothing to do in this case: textBuffer is correct! break; default: undoHistory = null; return false; } return _undoHistoryRegistry.TryGetHistory(textBuffer, out undoHistory); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.VisualStudio.LanguageServices.Implementation { using Workspace = Microsoft.CodeAnalysis.Workspace; [ExportWorkspaceServiceFactory(typeof(ITextUndoHistoryWorkspaceService), ServiceLayer.Host), Shared] internal class VisualStudioTextUndoHistoryWorkspaceServiceFactory : IWorkspaceServiceFactory { private readonly ITextUndoHistoryWorkspaceService _serviceSingleton; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextUndoHistoryWorkspaceServiceFactory(ITextUndoHistoryRegistry undoHistoryRegistry) => _serviceSingleton = new TextUndoHistoryWorkspaceService(undoHistoryRegistry); public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _serviceSingleton; private class TextUndoHistoryWorkspaceService : ITextUndoHistoryWorkspaceService { private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; public TextUndoHistoryWorkspaceService(ITextUndoHistoryRegistry undoHistoryRegistry) => _undoHistoryRegistry = undoHistoryRegistry; public bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory) { switch (editorWorkspace) { case VisualStudioWorkspaceImpl visualStudioWorkspace: // TODO: Handle undo if context changes var documentId = editorWorkspace.GetDocumentIdInCurrentContext(textBuffer.AsTextContainer()); if (documentId == null) { undoHistory = null; return false; } // In the Visual Studio case, there might be projection buffers involved for Venus, // where we associate undo history with the surface buffer and not the subject buffer. var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument != null) { textBuffer = containedDocument.DataBuffer; } break; case MiscellaneousFilesWorkspace _: // Nothing to do in this case: textBuffer is correct! break; default: undoHistory = null; return false; } return _undoHistoryRegistry.TryGetHistory(textBuffer, out undoHistory); } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Structure/Providers/IndexerDeclarationStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, 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 IndexerDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<IndexerDeclarationSyntax> { protected override void CollectBlockSpans( IndexerDeclarationSyntax indexerDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(indexerDeclaration, ref spans, optionProvider); // fault tolerance if (indexerDeclaration.AccessorList == null || indexerDeclaration.AccessorList.IsMissing || indexerDeclaration.AccessorList.OpenBraceToken.IsMissing || indexerDeclaration.AccessorList.CloseBraceToken.IsMissing) { return; } SyntaxNodeOrToken current = indexerDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Indexers are grouped together with properties in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.IsKind(SyntaxKind.IndexerDeclaration) || nextSibling.IsKind(SyntaxKind.PropertyDeclaration)); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( indexerDeclaration, indexerDeclaration.ParameterList.GetLastToken(includeZeroWidth: true), compressEmptyLines: compressEmptyLines, autoCollapse: true, type: BlockTypes.Member, isCollapsible: true)); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/DiaSymReader/Writer/ISymUnmanagedWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/SymbolVisitor`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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpSymbolVisitor<TResult> { public virtual TResult Visit(Symbol symbol) { return (object)symbol == null ? default(TResult) : symbol.Accept(this); } public virtual TResult DefaultVisit(Symbol symbol) { return default(TResult); } public virtual TResult VisitAlias(AliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitArrayType(ArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitAssembly(AssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDiscard(DiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitEvent(EventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitField(FieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLabel(LabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLocal(LocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitMethod(MethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitModule(ModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamedType(NamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamespace(NamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitParameter(ParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitPointerType(PointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitProperty(PropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpSymbolVisitor<TResult> { public virtual TResult Visit(Symbol symbol) { return (object)symbol == null ? default(TResult) : symbol.Accept(this); } public virtual TResult DefaultVisit(Symbol symbol) { return default(TResult); } public virtual TResult VisitAlias(AliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitArrayType(ArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitAssembly(AssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDynamicType(DynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitDiscard(DiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitEvent(EventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitField(FieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLabel(LabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitLocal(LocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitMethod(MethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitModule(ModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamedType(NamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitNamespace(NamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitParameter(ParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitPointerType(PointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitProperty(PropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitRangeVariable(RangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult VisitTypeParameter(TypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Shared/Utilities/SupportedPlatformData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class SupportedPlatformData { // Because completion finds lots of symbols that exist in // all projects, we'll instead maintain a list of projects // missing the symbol. public readonly List<ProjectId> InvalidProjects; public readonly IEnumerable<ProjectId> CandidateProjects; public readonly Workspace Workspace; public SupportedPlatformData(List<ProjectId> invalidProjects, IEnumerable<ProjectId> candidateProjects, Workspace workspace) { InvalidProjects = invalidProjects; CandidateProjects = candidateProjects; Workspace = workspace; } public IList<SymbolDisplayPart> ToDisplayParts() { if (InvalidProjects == null || InvalidProjects.Count == 0) { return SpecializedCollections.EmptyList<SymbolDisplayPart>(); } var builder = new List<SymbolDisplayPart>(); builder.AddLineBreak(); var projects = CandidateProjects.Select(p => Workspace.CurrentSolution.GetProject(p)).OrderBy(p => p.Name); foreach (var project in projects) { var text = string.Format(FeaturesResources._0_1, project.Name, Supported(!InvalidProjects.Contains(project.Id))); builder.AddText(text); builder.AddLineBreak(); } builder.AddLineBreak(); builder.AddText(FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts); return builder; } private static string Supported(bool supported) => supported ? FeaturesResources.Available : FeaturesResources.Not_Available; public bool HasValidAndInvalidProjects() => InvalidProjects.Any() && InvalidProjects.Count != CandidateProjects.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.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class SupportedPlatformData { // Because completion finds lots of symbols that exist in // all projects, we'll instead maintain a list of projects // missing the symbol. public readonly List<ProjectId> InvalidProjects; public readonly IEnumerable<ProjectId> CandidateProjects; public readonly Workspace Workspace; public SupportedPlatformData(List<ProjectId> invalidProjects, IEnumerable<ProjectId> candidateProjects, Workspace workspace) { InvalidProjects = invalidProjects; CandidateProjects = candidateProjects; Workspace = workspace; } public IList<SymbolDisplayPart> ToDisplayParts() { if (InvalidProjects == null || InvalidProjects.Count == 0) { return SpecializedCollections.EmptyList<SymbolDisplayPart>(); } var builder = new List<SymbolDisplayPart>(); builder.AddLineBreak(); var projects = CandidateProjects.Select(p => Workspace.CurrentSolution.GetProject(p)).OrderBy(p => p.Name); foreach (var project in projects) { var text = string.Format(FeaturesResources._0_1, project.Name, Supported(!InvalidProjects.Contains(project.Id))); builder.AddText(text); builder.AddLineBreak(); } builder.AddLineBreak(); builder.AddText(FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts); return builder; } private static string Supported(bool supported) => supported ? FeaturesResources.Available : FeaturesResources.Not_Available; public bool HasValidAndInvalidProjects() => InvalidProjects.Any() && InvalidProjects.Count != CandidateProjects.Count(); } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/PropertyDeclarationHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class PropertyDeclarationHighlighter Inherits AbstractKeywordHighlighter(Of PropertyStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Sub AddHighlights(propertyDeclaration As PropertyStatementSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) ' If the ancestor is not a property block, treat this as an auto-property. ' Otherwise, let the PropertyBlockHighlighter take over. Dim propertyBlock = propertyDeclaration.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock IsNot Nothing Then Return End If With propertyDeclaration Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword) highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End)) If .ImplementsClause IsNot Nothing Then highlights.Add(.ImplementsClause.ImplementsKeyword.Span) End If End With End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class PropertyDeclarationHighlighter Inherits AbstractKeywordHighlighter(Of PropertyStatementSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Sub AddHighlights(propertyDeclaration As PropertyStatementSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) ' If the ancestor is not a property block, treat this as an auto-property. ' Otherwise, let the PropertyBlockHighlighter take over. Dim propertyBlock = propertyDeclaration.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock IsNot Nothing Then Return End If With propertyDeclaration Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword) highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End)) If .ImplementsClause IsNot Nothing Then highlights.Add(.ImplementsClause.ImplementsKeyword.Span) End If End With End Sub End Class End Namespace
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenIfOperator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenIfOperator Inherits BasicTestBase ' Conditional operator as parameter <Fact> Public Sub ConditionalOperatorAsParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim a0 As Boolean = False Dim a1 As Integer = 0 Dim a2 As Long = 1 Dim b0 = a0 Dim b1 = a1 Dim b2 = a2 Console.WriteLine((If(b0, b1, b2)) &lt;&gt; (If(a0, a1, a2))) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ False ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 3 .locals init (Boolean V_0, //a0 Integer V_1, //a1 Long V_2, //a2 Object V_3, //b1 Object V_4) //b2 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: conv.i8 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: box "Boolean" IL_000d: ldloc.1 IL_000e: box "Integer" IL_0013: stloc.3 IL_0014: ldloc.2 IL_0015: box "Long" IL_001a: stloc.s V_4 IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0021: brtrue.s IL_0027 IL_0023: ldloc.s V_4 IL_0025: br.s IL_0028 IL_0027: ldloc.3 IL_0028: ldloc.0 IL_0029: brtrue.s IL_002e IL_002b: ldloc.2 IL_002c: br.s IL_0030 IL_002e: ldloc.1 IL_002f: conv.i8 IL_0030: box "Long" IL_0035: ldc.i4.0 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectNotEqual(Object, Object, Boolean) As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub ' Function call in return expression <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub FunctionCallAsArgument() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function C.fun_Exception(Integer) As System.Exception" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: call "Function C.fun_long(Integer) As Long" IL_0012: pop IL_0013: ldc.i4.1 IL_0014: call "Function C.fun_int(Integer) As Integer" IL_0019: conv.i8 IL_001a: pop IL_001b: ret }]]>) End Sub ' Lambda works in return argument <Fact()> Public Sub LambdaAsArgument_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim Y = 2 Dim S = If(True, _ Function(z As Integer) As Integer System.Console.WriteLine("SUB") Return z * z End Function, Y + 1) S = If(False, _ Sub(Z As Integer) System.Console.WriteLine("SUB") End Sub, Y + 1) System.Console.WriteLine(S) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (Object V_0) //Y IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001a: ldftn "Function C._Closure$__._Lambda$__0-0(Integer) As Integer" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C._Closure$__.$I0-0 As <generated method>" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: pop IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: box "Integer" IL_0038: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_003d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0042: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0047: call "Sub System.Console.WriteLine(Object)" IL_004c: ret } ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of Boolean, Long, Integer, Long)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult = testFunc(False, CLng(3), 100) Console.WriteLine(testResult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 100 ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of TestStruct, Long?, Integer, Integer?)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult1 = testFunc(New TestStruct(), Nothing, 10) Dim testResult2 = testFunc(New TestStruct(), 10, Nothing) Console.WriteLine (testResult1) Console.WriteLine (testResult2) End Sub End Module Public Structure TestStruct Public Shared Operator IsTrue(ts As TestStruct) As Boolean Return False End Operator Public Shared Operator IsFalse(ts As TestStruct) As Boolean Return True End Operator End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 10 0 ]]>).Compilation End Sub ' Multiple conditional operator in expression <Fact> Public Sub MultipleConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim S = If(False, 1, If(True, 2, 3)) Console.Write(S) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.Write(Object)" IL_0010: ret }]]>).Compilation End Sub ' Arguments are of types: bool, constant, enum <Fact> Public Sub EnumAsArguments() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim testResult = If(False, 0, color.Blue) Console.WriteLine(testResult) testResult = If(False, 5, color.Blue) Console.WriteLine(testResult) End Sub End Module Enum color Red Green Blue End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 2 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.WriteLine(Object)" IL_0010: ldc.i4.2 IL_0011: box "Integer" IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret }]]>).Compilation End Sub ' Implicit type conversion on conditional <Fact> Public Sub ImplicitConversionForConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim valueFromDatabase As Object Dim result As Decimal valueFromDatabase = DBNull.Value result = CDec(If(valueFromDatabase IsNot DBNull.Value, valueFromDatabase, 0)) Console.WriteLine(result) result = (If(valueFromDatabase IsNot DBNull.Value, CDec(valueFromDatabase), CDec(0))) Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (Object V_0) //valueFromDatabase IL_0000: ldsfld "System.DBNull.Value As System.DBNull" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld "System.DBNull.Value As System.DBNull" IL_000c: bne.un.s IL_0016 IL_000e: ldc.i4.0 IL_000f: box "Integer" IL_0014: br.s IL_0017 IL_0016: ldloc.0 IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_001c: call "Sub System.Console.WriteLine(Decimal)" IL_0021: ldloc.0 IL_0022: ldsfld "System.DBNull.Value As System.DBNull" IL_0027: bne.un.s IL_0030 IL_0029: ldsfld "Decimal.Zero As Decimal" IL_002e: br.s IL_0036 IL_0030: ldloc.0 IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_0036: call "Sub System.Console.WriteLine(Decimal)" IL_003b: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If("", x, 2) 'invalid s = If("True", x, 2) 'valid s = If("1", x, 2) 'valid End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr "" IL_0007: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_000c: pop IL_000d: ldstr "True" IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0017: pop IL_0018: ldstr "1" IL_001d: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0022: pop IL_0023: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument_2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(color.Green, x, 2) Console.WriteLine(S) s = If(color.Red, x, 2) Console.WriteLine(s) End Sub End Module Public Enum color Red Blue Green End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 ]]>) End Sub <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact> Public Sub FunctionWithNoReturnType() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(fun1(), x, 2) End Sub Private Function fun1() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0) //x IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: call "Function C.fun1() As Object" IL_000c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0011: brtrue.s IL_001b IL_0013: ldc.i4.2 IL_0014: box "Integer" IL_0019: br.s IL_001c IL_001b: ldloc.0 IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: pop IL_0022: ret }]]>).Compilation End Sub ' Const as conditional- argument <WorkItem(541452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541452")> <Fact()> Public Sub ConstAsArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Const con As Boolean = True Dim s1 = If(con, 1, 2) Console.Write(s1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Sub System.Console.Write(Integer)" IL_0006: ret } ]]>).Compilation End Sub ' Const i As Integer = IF <Fact> Public Sub AssignIfToConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const s As Integer = If(1>2, 9, 92) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF used in Redim <WorkItem(528563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528563")> <Fact> Public Sub IfUsedInRedim() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module Program Sub Main(args As String()) Dim s1 As Integer() ReDim Preserve s1(If(True, 10, 101)) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 .locals init (Integer() V_0) //s1 IL_0000: ldloc.0 IL_0001: ldc.i4.s 11 IL_0003: newarr "Integer" IL_0008: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array" IL_000d: castclass "Integer()" IL_0012: stloc.0 IL_0013: ret }]]>).Compilation End Sub ' IF on attribute <Fact> Public Sub IFOnAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System &lt;Assembly: CLSCompliant(If(True, False, True))&gt; Public Class base Public Shared sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyDiagnostics() End Sub ' #const val =if <Fact> Public Sub PredefinedConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Public Class Program Public Shared Sub Main() #Const ifconst = If(True, 1, 2) #If ifconst = 1 Then #End If End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF as function name <Fact> Public Sub IFAsFunctionName() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() End Sub Public Function [if](ByVal arg As String) As String Return arg End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.if", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }]]>).Compilation End Sub ' IF as Optional parameter <Fact()> Public Sub IFAsOptionalParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() goo() End Sub Public Sub goo(Optional ByVal arg As String = If(False, "6", "61")) System.Console.WriteLine(arg) End Sub End Module </file> </compilation>, expectedOutput:="61").Compilation End Sub ' IF used in For step <Fact()> Public Sub IFUsedInForStep() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim s10 As Boolean = False For c As Integer = 1 To 10 Step If(s10, 1, 2) Next End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) End Sub ' Passing IF as byref arg <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub IFAsByrefArg() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim X = "123" Dim Y = "456" Dim Z = If(1 > 2, goo(X), goo(Y)) End Sub Private Function goo(ByRef p1 As String) p1 = "HELLO" End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (String V_0, //X String V_1) //Y IL_0000: ldstr "123" IL_0005: stloc.0 IL_0006: ldstr "456" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: call "Function M1.goo(ByRef String) As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: pop IL_0019: ret }]]>) End Sub <WorkItem(541674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541674")> <Fact> Public Sub TypeConversionInRuntime() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Public Class Test Private Shared Sub Main() Dim a As Integer() = New Integer() {} Dim b As New List(Of Integer)() Dim c As IEnumerable(Of Integer) = If(a.Length > 0, a, DirectCast(b, IEnumerable(Of Integer))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll).VerifyIL("Test.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Integer() V_0, //a System.Collections.Generic.List(Of Integer) V_1) //b IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: stloc.0 IL_0007: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000c: stloc.1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: ldc.i4.0 IL_0011: bgt.s IL_0016 IL_0013: ldloc.1 IL_0014: pop IL_0015: ret IL_0016: ldloc.0 IL_0017: pop IL_0018: ret } ]]>).Compilation End Sub <WorkItem(541673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541673")> <Fact> Public Sub TypeConversionInRuntime_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Public Class AB2 Implements IB Public Function f() As Integer Implements IB.f Return 1 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB2..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB1..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (IB V_0) IL_0000: newobj "Sub AB1..ctor()" IL_0005: dup IL_0006: brtrue.s IL_0010 IL_0008: pop IL_0009: newobj "Sub AB1..ctor()" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt "Function IB.f() As Integer" IL_0015: box "Integer" IL_001a: pop IL_001b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(Derived.mask = 0, x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Derived.mask = 0, Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ldfld "Test1.x As IBase" IL_0014: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If (x, DirectCast(y, IBase)) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If (DirectCast(Me, IBase), y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class Test1 Implements IEnumerable Dim x As IEnumerator Dim y As IEnumerator Public Shared Sub Main() End Sub Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return If(Me IsNot Nothing, DirectCast(x, IEnumerator), DirectCast(y, IEnumerator)) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.GetEnumerator", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: ldarg.0 IL_0004: ldfld "Test1.y As System.Collections.IEnumerator" IL_0009: ret IL_000a: ldarg.0 IL_000b: ldfld "Test1.x As System.Collections.IEnumerator" IL_0010: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_4() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IBase Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1, //y IBase V_2) IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: ret } ]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_5() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IDerived), DirectCast(y, IDerived)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1) //y IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_6() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x = GetInterface() Dim y = GetInterface() Dim z = If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function Function GetInterface() As IBase Return Nothing End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 34 (0x22) .maxstack 1 .locals init (IBase V_0, //GetEnumerator Object V_1, //x Object V_2) //y IL_0000: ldarg.0 IL_0001: call "Function struct.GetInterface() As IBase" IL_0006: stloc.1 IL_0007: ldarg.0 IL_0008: call "Function struct.GetInterface() As IBase" IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0019 IL_0011: ldloc.2 IL_0012: castclass "IBase" IL_0017: br.s IL_001f IL_0019: ldloc.1 IL_001a: castclass "IBase" IL_001f: pop IL_0020: ldloc.0 IL_0021: ret }]]>).Compilation End Sub <Fact, WorkItem(545065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545065")> Public Sub IfOnConstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module BIFOpResult0011mod Public Sub scen7(Of T As Class)(ByVal arg As T) Dim s7_a As T = arg Dim s7_b As T = Nothing Dim s7_c = If(s7_a, s7_b) System.Console.Write(s7_c) End Sub Sub Main() scen7(Of String)("Q") End Sub End Module </file> </compilation>, expectedOutput:="Q").VerifyIL("BIFOpResult0011mod.scen7", <![CDATA[ { // Code size 30 (0x1e) .maxstack 2 .locals init (T V_0) //s7_b IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj "T" IL_0009: dup IL_000a: box "T" IL_000f: brtrue.s IL_0013 IL_0011: pop IL_0012: ldloc.0 IL_0013: box "T" IL_0018: call "Sub System.Console.Write(Object)" IL_001d: ret }]]>) End Sub <Fact> Public Sub IfOnUnconstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub Sub M2(Of T1, T2 As T1)(arg1 as T1, arg2 As T2) System.Console.WriteLine(If(arg2, arg1)) End Sub Sub Main() M1(Nothing, 1000) M1(1, 1000) M1(Nothing, "String Parameter 1") M1("String Parameter 2", "Should not print") M1(Of Integer?)(Nothing, 4) M1(Of Integer?)(5, 1000) M2(1000, 6) M2(Of Object, Integer?)(7, Nothing) M2(Of Object, Integer?)(1000, 8) M2(Of Integer?, Integer?)(9, Nothing) M2(Of Integer?, Integer?)(1000, 10) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 String Parameter 1 String Parameter 2 4 5 6 7 8 9 10 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: box "T" IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldarg.1 IL_000b: box "T" IL_0010: call "Sub System.Console.WriteLine(Object)" IL_0015: ret } ]]>).VerifyIL("Mod1.M2", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldarg.1 IL_0001: box "T2" IL_0006: brtrue.s IL_000b IL_0008: ldarg.0 IL_0009: br.s IL_0016 IL_000b: ldarg.1 IL_000c: box "T2" IL_0011: unbox.any "T1" IL_0016: box "T1" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParameterWithNothingLHS() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Mod1 Sub M1(Of T)(arg As T) Console.WriteLine(If(Nothing, arg)) End Sub Sub Main() ' Note that this behavior is different than C#'s behavior. This is consistent with Roslyn's handling ' of If(Nothing, 1), which will evaluate to 1 M1(1) Console.WriteLine(If(Nothing, 1)) M1("String Parameter 1") M1(Of Integer?)(3) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 1 String Parameter 1 3 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: box "T" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParametersOldLanguageVersion() CreateCompilation( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular15_5).AssertTheseDiagnostics(<![CDATA[ BC36716: Visual Basic 15.5 does not support unconstrained type parameters in binary conditional expressions. System.Console.WriteLine(If(arg1, arg2)) ~~~~~~~~~~~~~~ ]]>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenIfOperator Inherits BasicTestBase ' Conditional operator as parameter <Fact> Public Sub ConditionalOperatorAsParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim a0 As Boolean = False Dim a1 As Integer = 0 Dim a2 As Long = 1 Dim b0 = a0 Dim b1 = a1 Dim b2 = a2 Console.WriteLine((If(b0, b1, b2)) &lt;&gt; (If(a0, a1, a2))) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ False ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 70 (0x46) .maxstack 3 .locals init (Boolean V_0, //a0 Integer V_1, //a1 Long V_2, //a2 Object V_3, //b1 Object V_4) //b2 IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: conv.i8 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: box "Boolean" IL_000d: ldloc.1 IL_000e: box "Integer" IL_0013: stloc.3 IL_0014: ldloc.2 IL_0015: box "Long" IL_001a: stloc.s V_4 IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0021: brtrue.s IL_0027 IL_0023: ldloc.s V_4 IL_0025: br.s IL_0028 IL_0027: ldloc.3 IL_0028: ldloc.0 IL_0029: brtrue.s IL_002e IL_002b: ldloc.2 IL_002c: br.s IL_0030 IL_002e: ldloc.1 IL_002f: conv.i8 IL_0030: box "Long" IL_0035: ldc.i4.0 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectNotEqual(Object, Object, Boolean) As Object" IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0040: call "Sub System.Console.WriteLine(Object)" IL_0045: ret } ]]>).Compilation End Sub ' Function call in return expression <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub FunctionCallAsArgument() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim z = If(True, fun_Exception(1), fun_int(1)) Dim r = If(True, fun_long(0), fun_int(1)) Dim s = If(False, fun_long(0), fun_int(1)) End Sub Private Function fun_int(x As Integer) As Integer Return x End Function Private Function fun_long(x As Integer) As Long Return CLng(x) End Function Private Function fun_Exception(x As Integer) As Exception Return New Exception() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function C.fun_Exception(Integer) As System.Exception" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: call "Function C.fun_long(Integer) As Long" IL_0012: pop IL_0013: ldc.i4.1 IL_0014: call "Function C.fun_int(Integer) As Integer" IL_0019: conv.i8 IL_001a: pop IL_001b: ret }]]>) End Sub ' Lambda works in return argument <Fact()> Public Sub LambdaAsArgument_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim Y = 2 Dim S = If(True, _ Function(z As Integer) As Integer System.Console.WriteLine("SUB") Return z * z End Function, Y + 1) S = If(False, _ Sub(Z As Integer) System.Console.WriteLine("SUB") End Sub, Y + 1) System.Console.WriteLine(S) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (Object V_0) //Y IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C._Closure$__.$I0-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001a: ldftn "Function C._Closure$__._Lambda$__0-0(Integer) As Integer" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of Integer, Integer)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C._Closure$__.$I0-0 As <generated method>" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: pop IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: box "Integer" IL_0038: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_003d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0042: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0047: call "Sub System.Console.WriteLine(Object)" IL_004c: ret } ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of Boolean, Long, Integer, Long)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult = testFunc(False, CLng(3), 100) Console.WriteLine(testResult) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 100 ]]>).Compilation End Sub ' Conditional on expression tree <Fact()> Public Sub ExpressionTree_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Imports System Imports System.Linq.Expressions Module Program Sub Main(args As String()) Dim testExpr As Expression(Of Func(Of TestStruct, Long?, Integer, Integer?)) = Function(x, y, z) If(x, y, z) Dim testFunc = testExpr.Compile() Dim testResult1 = testFunc(New TestStruct(), Nothing, 10) Dim testResult2 = testFunc(New TestStruct(), 10, Nothing) Console.WriteLine (testResult1) Console.WriteLine (testResult2) End Sub End Module Public Structure TestStruct Public Shared Operator IsTrue(ts As TestStruct) As Boolean Return False End Operator Public Shared Operator IsFalse(ts As TestStruct) As Boolean Return True End Operator End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 10 0 ]]>).Compilation End Sub ' Multiple conditional operator in expression <Fact> Public Sub MultipleConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim S = If(False, 1, If(True, 2, 3)) Console.Write(S) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.Write(Object)" IL_0010: ret }]]>).Compilation End Sub ' Arguments are of types: bool, constant, enum <Fact> Public Sub EnumAsArguments() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim testResult = If(False, 0, color.Blue) Console.WriteLine(testResult) testResult = If(False, 5, color.Blue) Console.WriteLine(testResult) End Sub End Module Enum color Red Green Blue End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 2 2 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldc.i4.2 IL_0001: box "Integer" IL_0006: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_000b: call "Sub System.Console.WriteLine(Object)" IL_0010: ldc.i4.2 IL_0011: box "Integer" IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret }]]>).Compilation End Sub ' Implicit type conversion on conditional <Fact> Public Sub ImplicitConversionForConditional() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim valueFromDatabase As Object Dim result As Decimal valueFromDatabase = DBNull.Value result = CDec(If(valueFromDatabase IsNot DBNull.Value, valueFromDatabase, 0)) Console.WriteLine(result) result = (If(valueFromDatabase IsNot DBNull.Value, CDec(valueFromDatabase), CDec(0))) Console.WriteLine(result) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (Object V_0) //valueFromDatabase IL_0000: ldsfld "System.DBNull.Value As System.DBNull" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldsfld "System.DBNull.Value As System.DBNull" IL_000c: bne.un.s IL_0016 IL_000e: ldc.i4.0 IL_000f: box "Integer" IL_0014: br.s IL_0017 IL_0016: ldloc.0 IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_001c: call "Sub System.Console.WriteLine(Decimal)" IL_0021: ldloc.0 IL_0022: ldsfld "System.DBNull.Value As System.DBNull" IL_0027: bne.un.s IL_0030 IL_0029: ldsfld "Decimal.Zero As Decimal" IL_002e: br.s IL_0036 IL_0030: ldloc.0 IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal(Object) As Decimal" IL_0036: call "Sub System.Console.WriteLine(Decimal)" IL_003b: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If("", x, 2) 'invalid s = If("True", x, 2) 'valid s = If("1", x, 2) 'valid End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 36 (0x24) .maxstack 1 .locals init (Integer V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldstr "" IL_0007: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_000c: pop IL_000d: ldstr "True" IL_0012: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0017: pop IL_0018: ldstr "1" IL_001d: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(String) As Boolean" IL_0022: pop IL_0023: ret }]]>).Compilation End Sub ' Not boolean type as conditional-argument <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub NotBooleanAsConditionalArgument_2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(color.Green, x, 2) Console.WriteLine(S) s = If(color.Red, x, 2) Console.WriteLine(s) End Sub End Module Public Enum color Red Blue Green End Enum </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 ]]>) End Sub <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact> Public Sub FunctionWithNoReturnType() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module C Sub Main(args As String()) Dim x = 1 Dim s = If(fun1(), x, 2) End Sub Private Function fun1() End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0) //x IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: stloc.0 IL_0007: call "Function C.fun1() As Object" IL_000c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean" IL_0011: brtrue.s IL_001b IL_0013: ldc.i4.2 IL_0014: box "Integer" IL_0019: br.s IL_001c IL_001b: ldloc.0 IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0021: pop IL_0022: ret }]]>).Compilation End Sub ' Const as conditional- argument <WorkItem(541452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541452")> <Fact()> Public Sub ConstAsArgument() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main(args As String()) Const con As Boolean = True Dim s1 = If(con, 1, 2) Console.Write(s1) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Sub System.Console.Write(Integer)" IL_0006: ret } ]]>).Compilation End Sub ' Const i As Integer = IF <Fact> Public Sub AssignIfToConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const s As Integer = If(1>2, 9, 92) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF used in Redim <WorkItem(528563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528563")> <Fact> Public Sub IfUsedInRedim() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Imports System Module Program Sub Main(args As String()) Dim s1 As Integer() ReDim Preserve s1(If(True, 10, 101)) End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 .locals init (Integer() V_0) //s1 IL_0000: ldloc.0 IL_0001: ldc.i4.s 11 IL_0003: newarr "Integer" IL_0008: call "Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array" IL_000d: castclass "Integer()" IL_0012: stloc.0 IL_0013: ret }]]>).Compilation End Sub ' IF on attribute <Fact> Public Sub IFOnAttribute() CompileAndVerify( <compilation> <file name="a.vb"> Imports System &lt;Assembly: CLSCompliant(If(True, False, True))&gt; Public Class base Public Shared sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyDiagnostics() End Sub ' #const val =if <Fact> Public Sub PredefinedConst() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Public Class Program Public Shared Sub Main() #Const ifconst = If(True, 1, 2) #If ifconst = 1 Then #End If End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Program.Main", <![CDATA[ { // Code size 1 (0x1) .maxstack 0 IL_0000: ret }]]>).Compilation End Sub ' IF as function name <Fact> Public Sub IFAsFunctionName() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() End Sub Public Function [if](ByVal arg As String) As String Return arg End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.if", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }]]>).Compilation End Sub ' IF as Optional parameter <Fact()> Public Sub IFAsOptionalParameter() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Module M1 Sub Main() goo() End Sub Public Sub goo(Optional ByVal arg As String = If(False, "6", "61")) System.Console.WriteLine(arg) End Sub End Module </file> </compilation>, expectedOutput:="61").Compilation End Sub ' IF used in For step <Fact()> Public Sub IFUsedInForStep() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim s10 As Boolean = False For c As Integer = 1 To 10 Step If(s10, 1, 2) Next End Sub End Module </file> </compilation>, options:=TestOptions.ReleaseExe) End Sub ' Passing IF as byref arg <WorkItem(541647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541647")> <Fact()> Public Sub IFAsByrefArg() CompileAndVerify( <compilation> <file name="a.vb"> Module M1 Sub Main() Dim X = "123" Dim Y = "456" Dim Z = If(1 > 2, goo(X), goo(Y)) End Sub Private Function goo(ByRef p1 As String) p1 = "HELLO" End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("M1.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (String V_0, //X String V_1) //Y IL_0000: ldstr "123" IL_0005: stloc.0 IL_0006: ldstr "456" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: call "Function M1.goo(ByRef String) As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: pop IL_0019: ret }]]>) End Sub <WorkItem(541674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541674")> <Fact> Public Sub TypeConversionInRuntime() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Public Class Test Private Shared Sub Main() Dim a As Integer() = New Integer() {} Dim b As New List(Of Integer)() Dim c As IEnumerable(Of Integer) = If(a.Length > 0, a, DirectCast(b, IEnumerable(Of Integer))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll).VerifyIL("Test.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 2 .locals init (Integer() V_0, //a System.Collections.Generic.List(Of Integer) V_1) //b IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: stloc.0 IL_0007: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000c: stloc.1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: ldc.i4.0 IL_0011: bgt.s IL_0016 IL_0013: ldloc.1 IL_0014: pop IL_0015: ret IL_0016: ldloc.0 IL_0017: pop IL_0018: ret } ]]>).Compilation End Sub <WorkItem(541673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541673")> <Fact> Public Sub TypeConversionInRuntime_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Public Class AB2 Implements IB Public Function f() As Integer Implements IB.f Return 1 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB2(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB2..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(p, DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 29 (0x1d) .maxstack 1 .locals init (IB V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: newobj "Sub AB1..ctor()" IL_0008: br.s IL_0011 IL_000a: newobj "Sub AB1..ctor()" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: callvirt "Function IB.f() As Integer" IL_0016: box "Integer" IL_001b: pop IL_001c: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInRuntime_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Public Interface IB Function f() As Integer End Interface Public Class AB1 Implements IB Public Function f() As Integer Implements IB.f Return 42 End Function End Class Class MainClass Public Shared Sub g(p As Boolean) Dim x = (If(DirectCast(New AB1(), IB), DirectCast(New AB1(), IB))).f() End Sub Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("MainClass.g", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (IB V_0) IL_0000: newobj "Sub AB1..ctor()" IL_0005: dup IL_0006: brtrue.s IL_0010 IL_0008: pop IL_0009: newobj "Sub AB1..ctor()" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: callvirt "Function IB.f() As Integer" IL_0015: box "Integer" IL_001a: pop IL_001b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(Derived.mask = 0, x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Derived.mask = 0, Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ldfld "Test1.x As IBase" IL_0014: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 IL_0000: ldsfld "Derived.mask As Integer" IL_0005: brfalse.s IL_000e IL_0007: ldarg.0 IL_0008: ldfld "Test1.y As IBase" IL_000d: ret IL_000e: ldarg.0 IL_000f: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_1() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If(x, y) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If(Me, y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_2() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function m1() As IBase End Interface Class Derived Public Shared mask As Integer = 1 End Class Class Test1 Implements IBase Private y As IBase Private x As IBase Private cnt As Integer = 0 Public Sub New(link As IBase) x = Me y = link If y Is Nothing Then y = Me End If End Sub Public Shared Sub Main() End Sub Public Function m1() As IBase Implements IBase.m1 Return If (x, DirectCast(y, IBase)) End Function 'version1 (explicit impl in original repro) Public Function m2() As IBase Return If (DirectCast(Me, IBase), y) End Function 'version2 End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.m1", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Test1.x As IBase" IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.0 IL_000b: ldfld "Test1.y As IBase" IL_0010: ret }]]>).VerifyIL("Test1.m2", <![CDATA[ { // Code size 12 (0xc) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_000b IL_0004: pop IL_0005: ldarg.0 IL_0006: ldfld "Test1.y As IBase" IL_000b: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_3() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Imports System.Collections.Generic Class Test1 Implements IEnumerable Dim x As IEnumerator Dim y As IEnumerator Public Shared Sub Main() End Sub Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return If(Me IsNot Nothing, DirectCast(x, IEnumerator), DirectCast(y, IEnumerator)) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("Test1.GetEnumerator", <![CDATA[ { // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000a IL_0003: ldarg.0 IL_0004: ldfld "Test1.y As System.Collections.IEnumerator" IL_0009: ret IL_000a: ldarg.0 IL_000b: ldfld "Test1.x As System.Collections.IEnumerator" IL_0010: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_4() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IBase Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1, //y IBase V_2) IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: ret } ]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_5() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x As IDerived Dim y As IDerived Return If(x IsNot Nothing, DirectCast(x, IDerived), DirectCast(y, IDerived)) End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 .locals init (IDerived V_0, //x IDerived V_1) //y IL_0000: ldloc.0 IL_0001: brtrue.s IL_0005 IL_0003: ldloc.1 IL_0004: ret IL_0005: ldloc.0 IL_0006: ret }]]>).Compilation End Sub <Fact> Public Sub TypeConversionInterface_6() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer Off Interface IBase Function GetEnumerator() As IBase End Interface Interface IDerived Inherits IBase End Interface Structure struct Implements IDerived Public Shared Sub Main() End Sub Function GetEnumerator() As IBase Implements IBase.GetEnumerator Dim x = GetInterface() Dim y = GetInterface() Dim z = If(x IsNot Nothing, DirectCast(x, IBase), DirectCast(y, IBase)) End Function Function GetInterface() As IBase Return Nothing End Function End Structure </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("struct.GetEnumerator", <![CDATA[ { // Code size 34 (0x22) .maxstack 1 .locals init (IBase V_0, //GetEnumerator Object V_1, //x Object V_2) //y IL_0000: ldarg.0 IL_0001: call "Function struct.GetInterface() As IBase" IL_0006: stloc.1 IL_0007: ldarg.0 IL_0008: call "Function struct.GetInterface() As IBase" IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: brtrue.s IL_0019 IL_0011: ldloc.2 IL_0012: castclass "IBase" IL_0017: br.s IL_001f IL_0019: ldloc.1 IL_001a: castclass "IBase" IL_001f: pop IL_0020: ldloc.0 IL_0021: ret }]]>).Compilation End Sub <Fact, WorkItem(545065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545065")> Public Sub IfOnConstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module BIFOpResult0011mod Public Sub scen7(Of T As Class)(ByVal arg As T) Dim s7_a As T = arg Dim s7_b As T = Nothing Dim s7_c = If(s7_a, s7_b) System.Console.Write(s7_c) End Sub Sub Main() scen7(Of String)("Q") End Sub End Module </file> </compilation>, expectedOutput:="Q").VerifyIL("BIFOpResult0011mod.scen7", <![CDATA[ { // Code size 30 (0x1e) .maxstack 2 .locals init (T V_0) //s7_b IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj "T" IL_0009: dup IL_000a: box "T" IL_000f: brtrue.s IL_0013 IL_0011: pop IL_0012: ldloc.0 IL_0013: box "T" IL_0018: call "Sub System.Console.Write(Object)" IL_001d: ret }]]>) End Sub <Fact> Public Sub IfOnUnconstrainedMethodTypeParameter() CompileAndVerify( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub Sub M2(Of T1, T2 As T1)(arg1 as T1, arg2 As T2) System.Console.WriteLine(If(arg2, arg1)) End Sub Sub Main() M1(Nothing, 1000) M1(1, 1000) M1(Nothing, "String Parameter 1") M1("String Parameter 2", "Should not print") M1(Of Integer?)(Nothing, 4) M1(Of Integer?)(5, 1000) M2(1000, 6) M2(Of Object, Integer?)(7, Nothing) M2(Of Object, Integer?)(1000, 8) M2(Of Integer?, Integer?)(9, Nothing) M2(Of Integer?, Integer?)(1000, 10) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 String Parameter 1 String Parameter 2 4 5 6 7 8 9 10 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: box "T" IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldarg.1 IL_000b: box "T" IL_0010: call "Sub System.Console.WriteLine(Object)" IL_0015: ret } ]]>).VerifyIL("Mod1.M2", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 IL_0000: ldarg.1 IL_0001: box "T2" IL_0006: brtrue.s IL_000b IL_0008: ldarg.0 IL_0009: br.s IL_0016 IL_000b: ldarg.1 IL_000c: box "T2" IL_0011: unbox.any "T1" IL_0016: box "T1" IL_001b: call "Sub System.Console.WriteLine(Object)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParameterWithNothingLHS() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Mod1 Sub M1(Of T)(arg As T) Console.WriteLine(If(Nothing, arg)) End Sub Sub Main() ' Note that this behavior is different than C#'s behavior. This is consistent with Roslyn's handling ' of If(Nothing, 1), which will evaluate to 1 M1(1) Console.WriteLine(If(Nothing, 1)) M1("String Parameter 1") M1(Of Integer?)(3) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 1 String Parameter 1 3 ]]>).VerifyIL("Mod1.M1", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: box "T" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub IfOnUnconstrainedTypeParametersOldLanguageVersion() CreateCompilation( <compilation> <file name="a.vb"> Friend Module Mod1 Sub M1(Of T)(arg1 As T, arg2 As T) System.Console.WriteLine(If(arg1, arg2)) End Sub End Module </file> </compilation>, parseOptions:=TestOptions.Regular15_5).AssertTheseDiagnostics(<![CDATA[ BC36716: Visual Basic 15.5 does not support unconstrained type parameters in binary conditional expressions. System.Console.WriteLine(If(arg1, arg2)) ~~~~~~~~~~~~~~ ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ModuleKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ModuleKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassModuleParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateModuleParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodModuleParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ModuleKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassModuleParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateModuleParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodModuleParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/VisualBasic/Analyzers/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationDiagnosticAnalyzer.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.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicSimplifyObjectCreationDiagnosticAnalyzer Inherits AbstractBuiltInCodeStyleDiagnosticAnalyzer Public Sub New() MyBase.New( diagnosticId:=IDEDiagnosticIds.SimplifyObjectCreationDiagnosticId, enforceOnBuild:=EnforceOnBuildValues.SimplifyObjectCreation, [option]:=VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, language:=LanguageNames.VisualBasic, title:=New LocalizableResourceString(NameOf(VisualBasicAnalyzersResources.Object_creation_can_be_simplified), VisualBasicAnalyzersResources.ResourceManager, GetType(VisualBasicAnalyzersResources))) End Sub Protected Overrides Sub InitializeWorker(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeVariableDeclarator, SyntaxKind.VariableDeclarator) End Sub Public Overrides Function GetAnalyzerCategory() As DiagnosticAnalyzerCategory Return DiagnosticAnalyzerCategory.SemanticSpanAnalysis End Function Private Sub AnalyzeVariableDeclarator(context As SyntaxNodeAnalysisContext) ' Finds and reports syntax on the form: ' Dim x As SomeType = New SomeType() ' which can be simplified to ' Dim x As New SomeType() Dim node = context.Node Dim tree = node.SyntaxTree Dim cancellationToken = context.CancellationToken Dim styleOption = context.Options.GetOption(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, tree, cancellationToken) If Not styleOption.Value Then Return End If Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) Dim asClauseType = variableDeclarator.AsClause?.Type() If asClauseType Is Nothing Then Return End If Dim objectCreation = TryCast(variableDeclarator.Initializer?.Value, ObjectCreationExpressionSyntax) If objectCreation Is Nothing Then Return End If Dim symbolInfo = context.SemanticModel.GetTypeInfo(objectCreation, cancellationToken) If symbolInfo.Type IsNot Nothing AndAlso symbolInfo.Type.Equals(symbolInfo.ConvertedType, SymbolEqualityComparer.Default) Then context.ReportDiagnostic(DiagnosticHelper.Create(Descriptor, variableDeclarator.GetLocation(), styleOption.Notification.Severity, additionalLocations:=Nothing, properties:=Nothing)) End If 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.CodeStyle Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.CodeStyle Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicSimplifyObjectCreationDiagnosticAnalyzer Inherits AbstractBuiltInCodeStyleDiagnosticAnalyzer Public Sub New() MyBase.New( diagnosticId:=IDEDiagnosticIds.SimplifyObjectCreationDiagnosticId, enforceOnBuild:=EnforceOnBuildValues.SimplifyObjectCreation, [option]:=VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, language:=LanguageNames.VisualBasic, title:=New LocalizableResourceString(NameOf(VisualBasicAnalyzersResources.Object_creation_can_be_simplified), VisualBasicAnalyzersResources.ResourceManager, GetType(VisualBasicAnalyzersResources))) End Sub Protected Overrides Sub InitializeWorker(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeVariableDeclarator, SyntaxKind.VariableDeclarator) End Sub Public Overrides Function GetAnalyzerCategory() As DiagnosticAnalyzerCategory Return DiagnosticAnalyzerCategory.SemanticSpanAnalysis End Function Private Sub AnalyzeVariableDeclarator(context As SyntaxNodeAnalysisContext) ' Finds and reports syntax on the form: ' Dim x As SomeType = New SomeType() ' which can be simplified to ' Dim x As New SomeType() Dim node = context.Node Dim tree = node.SyntaxTree Dim cancellationToken = context.CancellationToken Dim styleOption = context.Options.GetOption(VisualBasicCodeStyleOptions.PreferSimplifiedObjectCreation, tree, cancellationToken) If Not styleOption.Value Then Return End If Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) Dim asClauseType = variableDeclarator.AsClause?.Type() If asClauseType Is Nothing Then Return End If Dim objectCreation = TryCast(variableDeclarator.Initializer?.Value, ObjectCreationExpressionSyntax) If objectCreation Is Nothing Then Return End If Dim symbolInfo = context.SemanticModel.GetTypeInfo(objectCreation, cancellationToken) If symbolInfo.Type IsNot Nothing AndAlso symbolInfo.Type.Equals(symbolInfo.ConvertedType, SymbolEqualityComparer.Default) Then context.ReportDiagnostic(DiagnosticHelper.Create(Descriptor, variableDeclarator.GetLocation(), styleOption.Notification.Severity, additionalLocations:=Nothing, properties:=Nothing)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/PEWriter/InheritedTypeParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal class InheritedTypeParameter : IGenericTypeParameter { private readonly ushort _index; private readonly ITypeDefinition _inheritingType; private readonly IGenericTypeParameter _parentParameter; internal InheritedTypeParameter(ushort index, ITypeDefinition inheritingType, IGenericTypeParameter parentParameter) { _index = index; _inheritingType = inheritingType; _parentParameter = parentParameter; } #region IGenericTypeParameter Members public ITypeDefinition DefiningType { get { return _inheritingType; } } #endregion #region IGenericParameter Members public IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context) { return _parentParameter.GetConstraints(context); } public bool MustBeReferenceType { get { return _parentParameter.MustBeReferenceType; } } public bool MustBeValueType { get { return _parentParameter.MustBeValueType; } } public bool MustHaveDefaultConstructor { get { return _parentParameter.MustHaveDefaultConstructor; } } public TypeParameterVariance Variance { get { return _inheritingType.IsInterface || _inheritingType.IsDelegate ? _parentParameter.Variance : TypeParameterVariance.NonVariant; } } #endregion #region ITypeDefinition Members public ushort Alignment { get { return 0; } } public bool HasDeclarativeSecurity { get { return false; } } public bool IsEnum { get { return false; } } public IArrayTypeReference? AsArrayTypeReference { get { return this as IArrayTypeReference; } } public IGenericMethodParameter? AsGenericMethodParameter { get { return this as IGenericMethodParameter; } } public IGenericMethodParameterReference? AsGenericMethodParameterReference { get { return this as IGenericMethodParameterReference; } } public IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get { return this as IGenericTypeInstanceReference; } } public IGenericTypeParameter? AsGenericTypeParameter { get { return this as IGenericTypeParameter; } } public IGenericTypeParameterReference? AsGenericTypeParameterReference { get { return this as IGenericTypeParameterReference; } } public INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) { return this as INamespaceTypeDefinition; } public INamespaceTypeReference? AsNamespaceTypeReference { get { return this as INamespaceTypeReference; } } public INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) { return this as INestedTypeDefinition; } public INestedTypeReference? AsNestedTypeReference { get { return this as INestedTypeReference; } } public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get { return this as ISpecializedNestedTypeReference; } } public IModifiedTypeReference? AsModifiedTypeReference { get { return this as IModifiedTypeReference; } } public IPointerTypeReference? AsPointerTypeReference { get { return this as IPointerTypeReference; } } public ITypeDefinition? AsTypeDefinition(EmitContext context) { return this as ITypeDefinition; } public IDefinition? AsDefinition(EmitContext context) { return this as IDefinition; } #endregion #region IReference Members CodeAnalysis.Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null; public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context) { return _parentParameter.GetAttributes(context); } public void Dispatch(MetadataVisitor visitor) { } #endregion #region ITypeReference Members public TypeDefinitionHandle TypeDef { get { return default(TypeDefinitionHandle); } } public bool IsAlias { get { return false; } } public bool IsValueType { get { return false; } } public ITypeDefinition GetResolvedType(EmitContext context) { throw ExceptionUtilities.Unreachable; } public PrimitiveTypeCode TypeCode { get { return PrimitiveTypeCode.NotPrimitive; } } #endregion #region IParameterListEntry Members public ushort Index { get { return _index; } } #endregion #region INamedEntity Members public string? Name { get { return _parentParameter.Name; } } #endregion #region IGenericTypeParameterReference Members ITypeReference IGenericTypeParameterReference.DefiningType { get { return _inheritingType; } } #endregion #region INamedTypeReference Members public bool MangleName { get { return false; } } #endregion public bool IsNested { get { throw ExceptionUtilities.Unreachable; } } public bool IsSpecializedNested { get { throw ExceptionUtilities.Unreachable; } } public ITypeReference UnspecializedVersion { get { throw ExceptionUtilities.Unreachable; } } public bool IsNamespaceTypeReference { get { throw ExceptionUtilities.Unreachable; } } public bool IsGenericTypeInstance { get { throw ExceptionUtilities.Unreachable; } } public sealed override bool Equals(object? obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection.Metadata; using Roslyn.Utilities; using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext; namespace Microsoft.Cci { internal class InheritedTypeParameter : IGenericTypeParameter { private readonly ushort _index; private readonly ITypeDefinition _inheritingType; private readonly IGenericTypeParameter _parentParameter; internal InheritedTypeParameter(ushort index, ITypeDefinition inheritingType, IGenericTypeParameter parentParameter) { _index = index; _inheritingType = inheritingType; _parentParameter = parentParameter; } #region IGenericTypeParameter Members public ITypeDefinition DefiningType { get { return _inheritingType; } } #endregion #region IGenericParameter Members public IEnumerable<TypeReferenceWithAttributes> GetConstraints(EmitContext context) { return _parentParameter.GetConstraints(context); } public bool MustBeReferenceType { get { return _parentParameter.MustBeReferenceType; } } public bool MustBeValueType { get { return _parentParameter.MustBeValueType; } } public bool MustHaveDefaultConstructor { get { return _parentParameter.MustHaveDefaultConstructor; } } public TypeParameterVariance Variance { get { return _inheritingType.IsInterface || _inheritingType.IsDelegate ? _parentParameter.Variance : TypeParameterVariance.NonVariant; } } #endregion #region ITypeDefinition Members public ushort Alignment { get { return 0; } } public bool HasDeclarativeSecurity { get { return false; } } public bool IsEnum { get { return false; } } public IArrayTypeReference? AsArrayTypeReference { get { return this as IArrayTypeReference; } } public IGenericMethodParameter? AsGenericMethodParameter { get { return this as IGenericMethodParameter; } } public IGenericMethodParameterReference? AsGenericMethodParameterReference { get { return this as IGenericMethodParameterReference; } } public IGenericTypeInstanceReference? AsGenericTypeInstanceReference { get { return this as IGenericTypeInstanceReference; } } public IGenericTypeParameter? AsGenericTypeParameter { get { return this as IGenericTypeParameter; } } public IGenericTypeParameterReference? AsGenericTypeParameterReference { get { return this as IGenericTypeParameterReference; } } public INamespaceTypeDefinition? AsNamespaceTypeDefinition(EmitContext context) { return this as INamespaceTypeDefinition; } public INamespaceTypeReference? AsNamespaceTypeReference { get { return this as INamespaceTypeReference; } } public INestedTypeDefinition? AsNestedTypeDefinition(EmitContext context) { return this as INestedTypeDefinition; } public INestedTypeReference? AsNestedTypeReference { get { return this as INestedTypeReference; } } public ISpecializedNestedTypeReference? AsSpecializedNestedTypeReference { get { return this as ISpecializedNestedTypeReference; } } public IModifiedTypeReference? AsModifiedTypeReference { get { return this as IModifiedTypeReference; } } public IPointerTypeReference? AsPointerTypeReference { get { return this as IPointerTypeReference; } } public ITypeDefinition? AsTypeDefinition(EmitContext context) { return this as ITypeDefinition; } public IDefinition? AsDefinition(EmitContext context) { return this as IDefinition; } #endregion #region IReference Members CodeAnalysis.Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null; public IEnumerable<ICustomAttribute> GetAttributes(EmitContext context) { return _parentParameter.GetAttributes(context); } public void Dispatch(MetadataVisitor visitor) { } #endregion #region ITypeReference Members public TypeDefinitionHandle TypeDef { get { return default(TypeDefinitionHandle); } } public bool IsAlias { get { return false; } } public bool IsValueType { get { return false; } } public ITypeDefinition GetResolvedType(EmitContext context) { throw ExceptionUtilities.Unreachable; } public PrimitiveTypeCode TypeCode { get { return PrimitiveTypeCode.NotPrimitive; } } #endregion #region IParameterListEntry Members public ushort Index { get { return _index; } } #endregion #region INamedEntity Members public string? Name { get { return _parentParameter.Name; } } #endregion #region IGenericTypeParameterReference Members ITypeReference IGenericTypeParameterReference.DefiningType { get { return _inheritingType; } } #endregion #region INamedTypeReference Members public bool MangleName { get { return false; } } #endregion public bool IsNested { get { throw ExceptionUtilities.Unreachable; } } public bool IsSpecializedNested { get { throw ExceptionUtilities.Unreachable; } } public ITypeReference UnspecializedVersion { get { throw ExceptionUtilities.Unreachable; } } public bool IsNamespaceTypeReference { get { throw ExceptionUtilities.Unreachable; } } public bool IsGenericTypeInstance { get { throw ExceptionUtilities.Unreachable; } } public sealed override bool Equals(object? obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/MSBuildTask/Csi.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Microsoft.Build.Framework; namespace Microsoft.CodeAnalysis.BuildTasks { public class Csi : InteractiveCompiler { #region Properties - Please keep these alphabetized. // These are the parameters specific to Csi. // The ones shared between Csi and Vbi are defined in InteractiveCompiler.cs, which is the base class. #endregion #region Tool Members /// <summary> /// Return the name of the tool to execute. /// </summary> protected override string ToolNameWithoutExtension => "csi"; #endregion #region Interactive Compiler Members protected override void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ","); commandLine.AppendSwitchIfNotNull("/loadpaths:", AdditionalLoadPaths, ","); commandLine.AppendSwitchIfNotNull("/imports:", Imports, ";"); Csc.AddReferencesToCommandLine(commandLine, References, isInteractive: true); base.AddResponseFileCommands(commandLine); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Microsoft.Build.Framework; namespace Microsoft.CodeAnalysis.BuildTasks { public class Csi : InteractiveCompiler { #region Properties - Please keep these alphabetized. // These are the parameters specific to Csi. // The ones shared between Csi and Vbi are defined in InteractiveCompiler.cs, which is the base class. #endregion #region Tool Members /// <summary> /// Return the name of the tool to execute. /// </summary> protected override string ToolNameWithoutExtension => "csi"; #endregion #region Interactive Compiler Members protected override void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ","); commandLine.AppendSwitchIfNotNull("/loadpaths:", AdditionalLoadPaths, ","); commandLine.AppendSwitchIfNotNull("/imports:", Imports, ";"); Csc.AddReferencesToCommandLine(commandLine, References, isInteractive: true); base.AddResponseFileCommands(commandLine); } #endregion } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/AbstractCSharpSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } 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. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } return false; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxToken.SyntaxIdentifierWithTrailingTrivia.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class SyntaxToken { internal class SyntaxIdentifierWithTrailingTrivia : SyntaxIdentifier { private readonly GreenNode _trailing; internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing) : base(text) { if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) : base(text, diagnostics, annotations) { if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } internal SyntaxIdentifierWithTrailingTrivia(ObjectReader reader) : base(reader) { var trailing = (GreenNode)reader.ReadValue(); if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } static SyntaxIdentifierWithTrailingTrivia() { ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifierWithTrailingTrivia), r => new SyntaxIdentifierWithTrailingTrivia(r)); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_trailing); } public override GreenNode GetTrailingTrivia() { return _trailing; } public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) { return new SyntaxIdentifierWithTrivia(this.Kind, this.TextField, this.TextField, trivia, _trailing, this.GetDiagnostics(), this.GetAnnotations()); } public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, trivia, this.GetDiagnostics(), this.GetAnnotations()); } internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, _trailing, diagnostics, this.GetAnnotations()); } internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, _trailing, this.GetDiagnostics(), annotations); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class SyntaxToken { internal class SyntaxIdentifierWithTrailingTrivia : SyntaxIdentifier { private readonly GreenNode _trailing; internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing) : base(text) { if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } internal SyntaxIdentifierWithTrailingTrivia(string text, GreenNode trailing, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) : base(text, diagnostics, annotations) { if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } internal SyntaxIdentifierWithTrailingTrivia(ObjectReader reader) : base(reader) { var trailing = (GreenNode)reader.ReadValue(); if (trailing != null) { this.AdjustFlagsAndWidth(trailing); _trailing = trailing; } } static SyntaxIdentifierWithTrailingTrivia() { ObjectBinder.RegisterTypeReader(typeof(SyntaxIdentifierWithTrailingTrivia), r => new SyntaxIdentifierWithTrailingTrivia(r)); } internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_trailing); } public override GreenNode GetTrailingTrivia() { return _trailing; } public override SyntaxToken TokenWithLeadingTrivia(GreenNode trivia) { return new SyntaxIdentifierWithTrivia(this.Kind, this.TextField, this.TextField, trivia, _trailing, this.GetDiagnostics(), this.GetAnnotations()); } public override SyntaxToken TokenWithTrailingTrivia(GreenNode trivia) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, trivia, this.GetDiagnostics(), this.GetAnnotations()); } internal override GreenNode SetDiagnostics(DiagnosticInfo[] diagnostics) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, _trailing, diagnostics, this.GetAnnotations()); } internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations) { return new SyntaxIdentifierWithTrailingTrivia(this.TextField, _trailing, this.GetDiagnostics(), annotations); } } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // If the session was created/maintained out of Roslyn, e.g. in debugger; no properties are set and we should use data.Snapshot. // However, we prefer using the original snapshot in some projection scenarios. var snapshotForDocument = Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation) ? triggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { // Try to find the chosen item has been most recently used. var bestItem = chosenItems.First(); for (int i = 0, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || c == '_'; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal class ItemManager : IAsyncCompletionItemManager { /// <summary> /// Used for filtering non-Roslyn data only. /// </summary> private readonly CompletionHelper _defaultCompletionHelper; private readonly RecentItemsManager _recentItemsManager; /// <summary> /// For telemetry. /// </summary> private readonly object _targetTypeCompletionFilterChosenMarker = new(); internal ItemManager(RecentItemsManager recentItemsManager) { // Let us make the completion Helper used for non-Roslyn items case-sensitive. // We can change this if get requests from partner teams. _defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true); _recentItemsManager = recentItemsManager; } public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionInitialDataSnapshot data, CancellationToken cancellationToken) { if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled) { AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled(); // This method is called exactly once, so use the opportunity to set a baseline for telemetry. if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))) { AsyncCompletionLogger.LogSessionContainsTargetTypeFilter(); } } if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled) { AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled(); } // Sort by default comparer of Roslyn CompletionItem var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray(); return Task.FromResult(sortedItems); } public Task<FilteredCompletionModel?> UpdateCompletionListAsync( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) => Task.FromResult(UpdateCompletionList(session, data, cancellationToken)); // We might need to handle large amount of items with import completion enabled, // so use a dedicated pool to minimize/avoid array allocations (especially in LOH) // Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be // called concurrently, which essentially makes the pooled list a singleton, // but we still use ObjectPool for concurrency handling just to be robust. private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool = new(factory: () => new(), size: 1); private FilteredCompletionModel? UpdateCompletionList( IAsyncCompletionSession session, AsyncCompletionSessionDataSnapshot data, CancellationToken cancellationToken) { if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions)) { // This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger. // For now, the default hasSuggestedItemOptions is false. hasSuggestedItemOptions = false; } hasSuggestedItemOptions |= data.DisplaySuggestionItem; var filterText = session.ApplicableToSpan.GetText(data.Snapshot); var reason = data.Trigger.Reason; var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger); // Check if the user is typing a number. If so, only proceed if it's a number // directly after a <dot>. That's because it is actually reasonable for completion // to be brought up after a <dot> and for the user to want to filter completion // items based on a number that exists in the name of the item. However, when // we are not after a dot (i.e. we're being brought up after <space> is typed) // then we don't want to filter things. Consider the user writing: // // dim i =<space> // // We'll bring up the completion list here (as VB has completion on <space>). // If the user then types '3', we don't want to match against Int32. if (filterText.Length > 0 && char.IsNumber(filterText[0])) { if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan)) { // Dismiss the session. return null; } } // We need to filter if // 1. a non-empty strict subset of filters are selected // 2. a non-empty set of expanders are unselected var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter); var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter); var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); // Make sure we only record one enabling of the filter per session session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker); } } var filterReason = Helpers.GetFilterReason(data.Trigger); // If the session was created/maintained out of Roslyn, e.g. in debugger; no properties are set and we should use data.Snapshot. // However, we prefer using the original snapshot in some projection scenarios. var snapshotForDocument = Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation) ? triggerLocation.Snapshot : data.Snapshot; var document = snapshotForDocument.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService<CompletionService>(); var completionRules = completionService?.GetRules() ?? CompletionRules.Default; var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper; // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed. // This conforms with the original VS 2010 behavior. if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion && data.Trigger.Reason == CompletionTriggerReason.Backspace && completionRules.DismissIfLastCharacterDeleted && session.ApplicableToSpan.GetText(data.Snapshot).Length == 0) { // Dismiss the session return null; } var options = document?.Project.Solution.Options; var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false; // Nothing to highlight if user hasn't typed anything yet. highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0; // Use a monotonically increasing integer to keep track the original alphabetical order of each item. var currentIndex = 0; var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate(); try { // Filter items based on the selected filters and matching. foreach (var item in data.InitialSortedList) { cancellationToken.ThrowIfCancellationRequested(); if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) { continue; } if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } if (TryCreateMatchResult( completionHelper, item, filterText, initialRoslynTriggerKind, filterReason, _recentItemsManager.RecentItems, highlightMatchingPortions: highlightMatchingPortions, currentIndex, out var matchResult)) { initialListOfItemsToBeIncluded.Add(matchResult); currentIndex++; } } if (initialListOfItemsToBeIncluded.Count == 0) { return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules); } // Sort the items by pattern matching results. // Note that we want to preserve the original alphabetical order for items with same pattern match score, // but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer // to `MatchResult` to achieve this. initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer); var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true; var updatedFilters = showCompletionItemFilters ? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters) : ImmutableArray<CompletionFilterWithState>.Empty; // If this was deletion, then we control the entire behavior of deletion ourselves. if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion) { return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod; if (completionService == null) { filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches); } else { filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text); } return HandleNormalFiltering( filterMethod, filterText, updatedFilters, filterReason, data.Trigger.Character, initialListOfItemsToBeIncluded, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper); } finally { // Don't call ClearAndFree, which resets the capacity to a default value. initialListOfItemsToBeIncluded.Clear(); s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded); } static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters) { if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) { return false; } return true; } static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders) { var associatedWithUnselectedExpander = false; foreach (var itemFilter in item.Filters) { if (itemFilter is CompletionExpander) { if (!unselectedExpanders.Contains(itemFilter)) { // If any of the associated expander is selected, the item should be included in the expanded list. return false; } associatedWithUnselectedExpander = true; } } // at this point, the item either: // 1. has no expander filter, therefore should be included // 2. or, all associated expanders are unselected, therefore should be excluded return associatedWithUnselectedExpander; } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) { var position = applicableToSpan.GetStartPoint(snapshot).Position; return position > 0 && snapshot[position - 1] == '.'; } private FilteredCompletionModel? HandleNormalFiltering( Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod, string filterText, ImmutableArray<CompletionFilterWithState> filters, CompletionFilterReason filterReason, char typeChar, List<MatchResult<VSCompletionItem>> itemsInList, bool hasSuggestedItemOptions, bool highlightMatchingPortions, CompletionHelper completionHelper) { // Not deletion. Defer to the language to decide which item it thinks best // matches the text typed so far. // Ask the language to determine which of the *matched* items it wants to select. var matchingItems = itemsInList.Where(r => r.MatchedFilterText) .SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch)); var chosenItems = filterMethod(matchingItems, filterText); int selectedItemIndex; VSCompletionItem? uniqueItem = null; MatchResult<VSCompletionItem> bestOrFirstMatchResult; if (chosenItems.Length == 0) { // We do not have matches: pick the one with longest common prefix or the first item from the list. selectedItemIndex = 0; bestOrFirstMatchResult = itemsInList[0]; var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); for (var i = 1; i < itemsInList.Count; ++i) { var item = itemsInList[i]; var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText); if (commonPrefixLength > longestCommonPrefixLength) { selectedItemIndex = i; bestOrFirstMatchResult = item; longestCommonPrefixLength = commonPrefixLength; } } } else { var recentItems = _recentItemsManager.RecentItems; // Of the items the service returned, pick the one most recently committed var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems); // Determine if we should consider this item 'unique' or not. A unique item // will be automatically committed if the user hits the 'invoke completion' // without bringing up the completion list. An item is unique if it was the // only item to match the text typed so far, and there was at least some text // typed. i.e. if we have "Console.$$" we don't want to commit something // like "WriteLine" since no filter text has actually been provided. However, // if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed. selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem)); bestOrFirstMatchResult = itemsInList[selectedItemIndex]; var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem()); if (deduplicatedListCount == 1 && filterText.Length > 0) { uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem; } } // Check that it is a filter symbol. We can be called for a non-filter symbol. // If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion // except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)). // In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion. if (filterReason == CompletionFilterReason.Insertion && !string.IsNullOrEmpty(filterText) && !string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) && !IsPotentialFilterCharacter(typeChar) && !Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText)) { return null; } var isHardSelection = IsHardSelection( filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions); var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters, updateSelectionHint, centerSelection: true, uniqueItem); } private static FilteredCompletionModel? HandleDeletionTrigger( CompletionTriggerReason filterTriggerKind, List<MatchResult<VSCompletionItem>> matchResults, string filterText, ImmutableArray<CompletionFilterWithState> filters, bool hasSuggestedItemOptions, bool highlightMatchingSpans, CompletionHelper completionHelper) { var matchingItems = matchResults.Where(r => r.MatchedFilterText); if (filterTriggerKind == CompletionTriggerReason.Insertion && !matchingItems.Any()) { // The user has typed something, but nothing in the actual list matched what // they were typing. In this case, we want to dismiss completion entirely. // The thought process is as follows: we aggressively brought up completion // to help them when they typed delete (in case they wanted to pick another // item). However, they're typing something that doesn't seem to match at all // The completion list is just distracting at this point. return null; } MatchResult<VSCompletionItem>? bestMatchResult = null; var moreThanOneMatchWithSamePriority = false; foreach (var currentMatchResult in matchingItems) { if (bestMatchResult == null) { // We had no best result yet, so this is now our best result. bestMatchResult = currentMatchResult; } else { var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText); if (match > 0) { moreThanOneMatchWithSamePriority = false; bestMatchResult = currentMatchResult; } else if (match == 0) { moreThanOneMatchWithSamePriority = true; } } } int index; bool hardSelect; // If we had a matching item, then pick the best of the matching items and // choose that one to be hard selected. If we had no actual matching items // (which can happen if the user deletes down to a single character and we // include everything), then we just soft select the first item. if (bestMatchResult != null) { // Only hard select this result if it's a prefix match // We need to do this so that // * deleting and retyping a dot in a member access does not change the // text that originally appeared before the dot // * deleting through a word from the end keeps that word selected // This also preserves the behavior the VB had through Dev12. hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase); index = matchResults.IndexOf(bestMatchResult.Value); } else { index = 0; hardSelect = false; } return new FilteredCompletionModel( GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters, hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected, centerSelection: true, uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem); } private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList( List<MatchResult<VSCompletionItem>> matchResults, string filterText, bool highlightMatchingPortions, CompletionHelper completionHelper) { return matchResults.SelectAsArray(matchResult => { var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions); return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans); }); static ImmutableArray<Span> GetHighlightedSpans( MatchResult<VSCompletionItem> matchResult, CompletionHelper completionHelper, string filterText, bool highlightMatchingPortions) { if (highlightMatchingPortions) { if (matchResult.RoslynCompletionItem.HasDifferentFilterText) { // The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText, // which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again. // However, if the Roslyn item's FilterText is different from its DisplayText, // we need to do the match against the display text of the VS item directly to get the highlighted spans. return completionHelper.GetHighlightedSpans( matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan()); } var patternMatch = matchResult.PatternMatch; if (patternMatch.HasValue) { // Since VS item's display text is created as Prefix + DisplayText + Suffix, // we can calculate the highlighted span by adding an offset that is the length of the Prefix. return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem); } } // If there's no match for Roslyn item's filter text which is identical to its display text, // then we can safely assume there'd be no matching to VS item's display text. return ImmutableArray<Span>.Empty; } } private static FilteredCompletionModel? HandleAllItemsFilteredOut( CompletionTriggerReason triggerReason, ImmutableArray<CompletionFilterWithState> filters, CompletionRules completionRules) { if (triggerReason == CompletionTriggerReason.Insertion) { // If the user was just typing, and the list went to empty *and* this is a // language that wants to dismiss on empty, then just return a null model // to stop the completion session. if (completionRules.DismissIfEmpty) { return null; } } // If the user has turned on some filtering states, and we filtered down to // nothing, then we do want the UI to show that to them. That way the user // can turn off filters they don't want and get the right set of items. // If we are going to filter everything out, then just preserve the existing // model (and all the previously filtered items), but switch over to soft // selection. var selection = UpdateSelectionHint.SoftSelected; return new FilteredCompletionModel( ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0, filters, selection, centerSelection: true, uniqueItem: null); } private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters( List<MatchResult<VSCompletionItem>> filteredList, ImmutableArray<CompletionFilterWithState> filters) { // See which filters might be enabled based on the typed code using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters); textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters)); // When no items are available for a given filter, it becomes unavailable. // Expanders always appear available as long as it's presented. return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// <summary> /// Given multiple possible chosen completion items, pick the one that has the /// best MRU index. /// </summary> private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU( ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems) { // Try to find the chosen item has been most recently used. var bestItem = chosenItems.First(); for (int i = 0, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var mruIndex1 = GetRecentItemIndex(recentItems, bestItem); var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem); if ((mruIndex2 < mruIndex1) || (mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } // If our best item appeared in the MRU list, use it if (GetRecentItemIndex(recentItems, bestItem) <= 0) { return bestItem; } // Otherwise use the chosen item that has the highest // matchPriority. for (int i = 1, n = chosenItems.Length; i < n; i++) { var chosenItem = chosenItems[i]; var bestItemPriority = bestItem.Rules.MatchPriority; var currentItemPriority = chosenItem.Rules.MatchPriority; if ((currentItemPriority > bestItemPriority) || ((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem())) { bestItem = chosenItem; } } return bestItem; } private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item) { var index = recentItems.IndexOf(item.FilterText); return -index; } private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem) { if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem)) { roslynItem = RoslynCompletionItem.Create( displayText: vsItem.DisplayText, filterText: vsItem.FilterText, sortText: vsItem.SortText, displayTextSuffix: vsItem.Suffix); vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem); } return roslynItem; } private static bool TryCreateMatchResult( CompletionHelper completionHelper, VSCompletionItem item, string filterText, CompletionTriggerKind initialTriggerKind, CompletionFilterReason filterReason, ImmutableArray<string> recentItems, bool highlightMatchingPortions, int currentIndex, out MatchResult<VSCompletionItem> matchResult) { var roslynItem = GetOrAddRoslynCompletionItem(item); return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult); } // PERF: Create a singleton to avoid lambda allocation on hot path private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter = (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan(); private static bool IsHardSelection( string filterText, RoslynCompletionItem item, bool matchedFilterText, bool useSuggestionMode) { if (item == null || useSuggestionMode) { return false; } // We don't have a builder and we have a best match. Normally this will be hard // selected, except for a few cases. Specifically, if no filter text has been // provided, and this is not a preselect match then we will soft select it. This // happens when the completion list comes up implicitly and there is something in // the MRU list. In this case we do want to select it, but not with a hard // selection. Otherwise you can end up with the following problem: // // dim i as integer =<space> // // Completion will comes up after = with 'integer' selected (Because of MRU). We do // not want 'space' to commit this. // If all that has been typed is punctuation, then don't hard select anything. // It's possible the user is just typing language punctuation and selecting // anything in the list will interfere. We only allow this if the filter text // exactly matches something in the list already. if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText) { return false; } // If the user hasn't actually typed anything, then don't hard select any item. // The only exception to this is if the completion provider has requested the // item be preselected. if (filterText.Length == 0) { // Item didn't want to be hard selected with no filter text. // So definitely soft select it. if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection) { return false; } // Item did not ask to be preselected. So definitely soft select it. if (item.Rules.MatchPriority == MatchPriority.Default) { return false; } } // The user typed something, or the item asked to be preselected. In // either case, don't soft select this. Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default); // If the user moved the caret left after they started typing, the 'best' match may not match at all // against the full text span that this item would be replacing. if (!matchedFilterText) { return false; } // There was either filter text, or this was a preselect match. In either case, we // can hard select this. return true; } private static bool IsAllPunctuation(string filterText) { foreach (var ch in filterText) { if (!char.IsPunctuation(ch)) { return false; } } return true; } /// <summary> /// A potential filter character is something that can filter a completion lists and is /// *guaranteed* to not be a commit character. /// </summary> private static bool IsPotentialFilterCharacter(char c) { // TODO(cyrusn): Actually use the right Unicode categories here. return char.IsLetter(c) || char.IsNumber(c) || c == '_'; } } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Shared/TestHooks/IAsyncToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal interface IAsyncToken : IDisposable { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Shared.TestHooks { internal interface IAsyncToken : IDisposable { } }
-1
dotnet/roslyn
54,983
Fix 'syntax generator' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:29:23Z
2021-07-20T20:38:29Z
0b3129913a7985c099d9d60f777f650fe99b4ad0
459fff0a5a455ad0232dea6fe886760061aaaedf
Fix 'syntax generator' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/DirectiveSyntaxEqualityComparer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class DirectiveSyntaxEqualityComparer Implements IEqualityComparer(Of DirectiveTriviaSyntax) Public Shared ReadOnly Instance As New DirectiveSyntaxEqualityComparer Private Sub New() End Sub Public Shadows Function Equals(x As DirectiveTriviaSyntax, y As DirectiveTriviaSyntax) As Boolean Implements IEqualityComparer(Of DirectiveTriviaSyntax).Equals Return x.SpanStart = y.SpanStart End Function Public Shadows Function GetHashCode(obj As DirectiveTriviaSyntax) As Integer Implements IEqualityComparer(Of DirectiveTriviaSyntax).GetHashCode Return obj.SpanStart 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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class DirectiveSyntaxEqualityComparer Implements IEqualityComparer(Of DirectiveTriviaSyntax) Public Shared ReadOnly Instance As New DirectiveSyntaxEqualityComparer Private Sub New() End Sub Public Shadows Function Equals(x As DirectiveTriviaSyntax, y As DirectiveTriviaSyntax) As Boolean Implements IEqualityComparer(Of DirectiveTriviaSyntax).Equals Return x.SpanStart = y.SpanStart End Function Public Shadows Function GetHashCode(obj As DirectiveTriviaSyntax) As Integer Implements IEqualityComparer(Of DirectiveTriviaSyntax).GetHashCode Return obj.SpanStart End Function End Class End Namespace
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using Basic.Reference.Assemblies; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" namespace System { public class Object {} public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { public Exception(string s){} } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Disable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:disable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, IEnumerable<ISourceGenerator> generators = null, GeneratorDriverCache driverCache = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif private static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) { var minSystemCollectionsImmutableSource = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] namespace System.Collections.Immutable { public struct ImmutableArray<T> { } } "; var minCodeAnalysisSource = @" using System; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Microsoft.CodeAnalysis.Diagnostics { [AttributeUsage(AttributeTargets.Class)] public sealed class DiagnosticAnalyzerAttribute : Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public abstract class DiagnosticAnalyzer { public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void Initialize(AnalysisContext context); } public abstract class AnalysisContext { } } namespace Microsoft.CodeAnalysis { public sealed class DiagnosticDescriptor { } } "; var minSystemCollectionsImmutableImage = CSharpCompilation.Create( "System.Collections.Immutable", new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, new MetadataReference[] { NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); var minCodeAnalysisImage = CSharpCompilation.Create( "Microsoft.CodeAnalysis", new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, new MetadataReference[] { NetStandard13.SystemRuntime, minSystemCollectionsImmutableRef }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); var analyzerSource = @" using System; using System.Collections.ObjectModel; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Win32.SafeHandles; [DiagnosticAnalyzer(""C#"")] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[] { typeof(Win32Exception), // Microsoft.Win32.Primitives typeof(AppContext), // System.AppContext typeof(Console), // System.Console typeof(ValueTuple), // System.ValueTuple typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo typeof(Process), // System.Diagnostics.Process typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars typeof(ZipArchive), // System.IO.Compression typeof(ZipFile), // System.IO.Compression.ZipFile typeof(FileOptions), // System.IO.FileSystem typeof(FileAttributes), // System.IO.FileSystem.Primitives typeof(HttpClient), // System.Net.Http typeof(AuthenticatedStream), // System.Net.Security typeof(IOControlCode), // System.Net.Sockets typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation typeof(SerializationException), // System.Runtime.Serialization.Primitives typeof(GenericIdentity), // System.Security.Claims typeof(Aes), // System.Security.Cryptography.Algorithms typeof(CspParameters), // System.Security.Cryptography.Csp typeof(AsnEncodedData), // System.Security.Cryptography.Encoding typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates typeof(IXmlLineInfo), // System.Xml.ReaderWriter typeof(XmlNode), // System.Xml.XmlDocument typeof(XPathDocument), // System.Xml.XPath typeof(XDocumentExtensions), // System.Xml.XPath.XDocument typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages typeof(ValueTask<>), // System.Threading.Tasks.Extensions // csc doesn't ship with facades for the following assemblies. // Analyzers can't use them unless they carry the facade with them. // typeof(SafePipeHandle), // System.IO.Pipes // typeof(StackFrame), // System.Diagnostics.StackTrace // typeof(BindingFlags), // System.Reflection.TypeExtensions // typeof(AccessControlActions), // System.Security.AccessControl // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows // typeof(Thread), // System.Threading.Thread }.Length.ToString()); public override void Initialize(AnalysisContext context) { } }"; var references = new MetadataReference[] { minCodeAnalysisRef, minSystemCollectionsImmutableRef }; references = references.Concat(NetStandard13.All).ToArray(); var analyzerImage = CSharpCompilation.Create( analyzerAssemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, references: references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); return analyzerImage; } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerSemanticWarning() { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" var expectedWarningCount = expectedAnalyzerExecution ? 3 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Resources.Proprietary; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; using Basic.Reference.Assemblies; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; using static Roslyn.Test.Utilities.SharedResourceHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests { public class CommandLineTests : CommandLineTestBase { #if NETCOREAPP private static readonly string s_CSharpCompilerExecutable; private static readonly string s_DotnetCscRun; #else private static readonly string s_CSharpCompilerExecutable = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.exe")); private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty; #endif private static readonly string s_CSharpScriptExecutable; private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests)); static CommandLineTests() { #if NETCOREAPP var cscDllPath = Path.Combine( Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location), Path.Combine("dependency", "csc.dll")); var dotnetExe = DotNetCoreSdk.ExePath; var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies() .FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location; var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath); // Since we are using references based on the UnitTest's runtime, we need to use // its runtime config when executing out program. var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json"); s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll"""; s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}"""; s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll")); #else s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe")); #endif } private class TestCommandLineParser : CSharpCommandLineParser { private readonly Dictionary<string, string> _responseFiles; private readonly Dictionary<string, string[]> _recursivePatterns; private readonly Dictionary<string, string[]> _patterns; public TestCommandLineParser( Dictionary<string, string> responseFiles = null, Dictionary<string, string[]> patterns = null, Dictionary<string, string[]> recursivePatterns = null, bool isInteractive = false) : base(isInteractive) { _responseFiles = responseFiles; _recursivePatterns = recursivePatterns; _patterns = patterns; } internal override IEnumerable<string> EnumerateFiles(string directory, string fileNamePattern, SearchOption searchOption) { var key = directory + "|" + fileNamePattern; if (searchOption == SearchOption.TopDirectoryOnly) { return _patterns[key]; } else { return _recursivePatterns[key]; } } internal override TextReader CreateTextFileReader(string fullPath) { return new StringReader(_responseFiles[fullPath]); } } private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory) { return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory); } private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null) { sdkDirectory = sdkDirectory ?? SdkDirectory; var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true); return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } [ConditionalFact(typeof(WindowsDesktopOnly))] [WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")] public void SuppressedWarnAsErrorsStillEmit() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" #pragma warning disable 1591 public class P { public static void Main() {} }"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); string exePath = Path.Combine(dir.Path, "temp.exe"); Assert.True(File.Exists(exePath)); var result = ProcessUtilities.Run(exePath, arguments: ""); Assert.Equal(0, result.ExitCode); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void XmlMemoryMapped() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C {}"); const string docName = "doc.xml"; var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var xmlPath = Path.Combine(dir.Path, docName); using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true)) { exitCode = cmd.Run(outWriter); Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString()); Assert.Equal(1, exitCode); } } [Fact] public void SimpleAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = none dotnet_diagnostic.Warning01.severity = none my_option = my_val [*.txt] dotnet_diagnostic.cs0169.severity = none my_option2 = my_val2"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032", "/additionalfile:" + additionalFile.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider; Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Suppress, severity); var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = analyzerOptions.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option", out string val)); Assert.Equal("my_val", val); Assert.False(options.TryGetValue("my_option2", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.True(options.TryGetValue("my_option2", out val)); Assert.Equal("my_val2", val); Assert.False(options.TryGetValue("my_option", out _)); Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _)); } [Fact] public void AnalyzerConfigBadSeverity() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = garbage"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal( $@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'. test.cs(4,9): warning CS0169: The field 'C._f' is never used ", outWriter.ToString()); Assert.Null(cmd.AnalyzerOptions); } [Fact] public void AnalyzerConfigsInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" [*.cs] dotnet_diagnostic.cs0169.severity = suppress"; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').", outWriter.ToString().TrimEnd()); } // This test should only run when the machine's default encoding is shift-JIS [ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompileShiftJisOnShiftJis() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path }); Assert.Null(cmd.Arguments.Encoding); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RunWithShiftJisFile() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path }); Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString()); var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path); Assert.Equal(0, result.ExitCode); Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932))); } [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CompilerBinariesAreAnyCPU() { Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture); } [Fact] public void ResponseFiles1() { string rsp = Temp.CreateFile().WriteAllText(@" /r:System.dll /nostdlib # this is ignored System.Console.WriteLine(""*?""); # this is error a.cs ").Path; var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" }); cmd.Arguments.Errors.Verify( // error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);")); AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path)); CleanupAllGeneratedFiles(rsp); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void ResponseFiles_RelativePaths() { var parentDir = Temp.CreateDirectory(); var baseDir = parentDir.CreateDirectory("temp"); var dirX = baseDir.CreateDirectory("x"); var dirAB = baseDir.CreateDirectory("a b"); var dirSubDir = baseDir.CreateDirectory("subdir"); var dirGoo = parentDir.CreateDirectory("goo"); var dirBar = parentDir.CreateDirectory("bar"); string basePath = baseDir.Path; Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName); var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>() { { prependBasePath(@"a.rsp"), @" ""@subdir\b.rsp"" /r:..\v4.0.30319\System.dll /r:.\System.Data.dll a.cs @""..\c.rsp"" @\d.rsp /libpaths:..\goo;../bar;""a b"" " }, { Path.Combine(dirSubDir.Path, @"b.rsp"), @" b.cs " }, { prependBasePath(@"..\c.rsp"), @" c.cs /lib:x " }, { Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @" # comment d.cs " } }, isInteractive: false); var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory); args.Errors.Verify(); Assert.False(args.IsScriptRunner); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray(); AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles); AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references); AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray()); Assert.Equal(basePath, args.BaseDirectory); } #nullable enable [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryNotAddedToKeyFileSearchPaths() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } [ConditionalFact(typeof(WindowsOnly))] public void NullBaseDirectoryWithAdditionalFiles_Wildcard() { var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory); AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths); Assert.Null(parser.OutputDirectory); parser.Errors.Verify( // error CS2001: Source file '*' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1), // error CS8762: Output directory could not be determined Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1) ); } #nullable disable [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPath() { var parentDir = Temp.CreateDirectory(); var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null); AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths); } [Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")] public void NoSdkPathReferenceSystemDll() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" }); var exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim()); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns() { var parser = new TestCommandLineParser( patterns: new Dictionary<string, string[]>() { { @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } } }, recursivePatterns: new Dictionary<string, string[]>() { { @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } }, }); var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory); args.Errors.Verify(); string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles); } [Fact] public void ParseQuotedMainType() { // Verify the main switch are unquoted when used because of the issue with // MSBuild quoting some usages and not others. A quote character is not valid in either // these names. CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test", args.CompilationOptions.MainTypeName); args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName); // Use of Cyrillic namespace args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path); args.Errors.Verify(); Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName); } [Fact] [WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")] public void ArgumentStartWithDashAndContainingSlash() { CSharpCommandLineArguments args; var folder = Temp.CreateDirectory(); args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path); args.Errors.Verify( // error CS2007: Unrecognized option: '-debug+/debug:portable' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); } [WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")] [WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")] [ConditionalFact(typeof(WindowsOnly))] public void SourceFiles_Patterns2() { var folder = Temp.CreateDirectory(); CreateFile(folder, "a.cs"); CreateFile(folder, "b.vb"); CreateFile(folder, "c.cpp"); var folderA = folder.CreateDirectory("A"); CreateFile(folderA, "A_a.cs"); CreateFile(folderA, "A_b.cs"); CreateFile(folderA, "A_c.vb"); var folderB = folder.CreateDirectory("B"); CreateFile(folderB, "B_a.cs"); CreateFile(folderB, "B_b.vb"); CreateFile(folderB, "B_c.cpx"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim()); CSharpCommandLineArguments args; string[] resolvedSourceFiles; args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles); args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path); args.Errors.Verify(); resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray(); Assert.Equal(4, resolvedSourceFiles.Length); } [ConditionalFact(typeof(WindowsOnly))] public void SourceFile_BadPath() { var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory); Assert.Equal(3, args.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code); Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code); Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code); } private void CreateFile(TempDirectory folder, string file) { var f = folder.CreateFile(file); f.WriteAllText(""); } [Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")] public void Win32ResourceArguments() { string[] args = new string[] { @"/win32manifest:..\here\there\everywhere\nonexistent" }; var parsedArgs = DefaultParse(args, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:\bogus" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32Res:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32icon:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); args = new string[] { @"/Win32manifest:goo.win32data:bar.win32data2" }; parsedArgs = DefaultParse(args, WorkingDirectory); CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code); Assert.Equal(2, errors.First().Arguments.Count()); } [Fact] public void Win32ResConflicts() { var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code); Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count); parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.True(parsedArgs.NoWin32Manifest); Assert.Null(parsedArgs.Win32Manifest); } [Fact] public void Win32ResInvalid() { var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res")); parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+")); parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon")); parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+")); parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest")); parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+")); } [Fact] public void Win32IconContainsGarbage() { string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path; var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory); var compilation = CreateCompilation(new SyntaxTree[0]); IEnumerable<DiagnosticInfo> errors; CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors); Assert.Equal(1, errors.Count()); Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code); Assert.Equal(1, errors.First().Arguments.Count()); CleanupAllGeneratedFiles(tmpFileName); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Win32ResQuotes() { string[] responseFile = new string[] { @" /win32res:d:\\""abc def""\a""b c""d\a.res", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile); responseFile = new string[] { @" /win32icon:d:\\""abc def""\a""b c""d\a.ico", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon); responseFile = new string[] { @" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest", }; args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseResources() { var diags = new List<Diagnostic>(); ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"some File.goo.bar", desc.FileName); Assert.Equal("someName", desc.ResourceName); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("some Name", desc.ResourceName); Assert.True(desc.IsPublic); // Use file name in place of missing resource name. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Quoted accessibility is fine. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false); Assert.Equal(0, diags.Count); Assert.Equal(@"someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // Leading commas are not ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar")); diags.Clear(); Assert.Null(desc); // Trailing commas are ignored... desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); // ...even if there's whitespace between them. desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("someFile.goo.bar", desc.FileName); Assert.Equal("someFile.goo.bar", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false); diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("")); Assert.Null(desc); diags.Clear(); desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.True(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false); diags.Verify( // CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe) // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private' Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" ")); diags.Clear(); Assert.Null(desc); desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false); diags.Verify(); diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal("path", desc.ResourceName); Assert.False(desc.IsPublic); desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2005: Missing file specification for '' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1)); diags.Clear(); Assert.Null(desc); var longE = new String('e', 1024); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false); diags.Verify(); // Now checked during emit. diags.Clear(); Assert.Equal("path", desc.FileName); Assert.Equal(longE, desc.ResourceName); Assert.False(desc.IsPublic); var longI = new String('i', 260); desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false); diags.Verify( // error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1)); } [Fact] public void ManagedResourceOptions() { CSharpCommandLineArguments parsedArgs; ResourceDescription resourceDescription; parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("a", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Null(resourceDescription.FileName); // since embedded Assert.Equal("b", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("c", resourceDescription.FileName); Assert.Equal("c", resourceDescription.ResourceName); parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); resourceDescription = parsedArgs.ManifestResources.Single(); Assert.Equal("d", resourceDescription.FileName); Assert.Equal("d", resourceDescription.ResourceName); } [Fact] public void ManagedResourceOptions_SimpleErrors() { var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:")); parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res")); parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+")); parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:")); parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:")); parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres")); parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+")); parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:")); } [Fact] public void Link_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:")); parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L")); parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+")); parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:")); } [ConditionalFact(typeof(WindowsOnly))] public void Recurse_SimpleTests() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); var file2 = dir.CreateFile("b.cs"); var file3 = dir.CreateFile("c.txt"); var file4 = dir.CreateDirectory("d1").CreateFile("d.txt"); var file5 = dir.CreateDirectory("d2").CreateFile("e.cs"); file1.WriteAllText(""); file2.WriteAllText(""); file3.WriteAllText(""); file4.WriteAllText(""); file5.WriteAllText(""); var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString()); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" }, parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}"))); parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:")); parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:")); parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse")); parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+")); parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:")); CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); CleanupAllGeneratedFiles(file3.Path); CleanupAllGeneratedFiles(file4.Path); CleanupAllGeneratedFiles(file5.Path); } [Fact] public void Reference_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "a", "b", "c" }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { " b " }, parsedArgs.MetadataReferences. Where((res) => !res.Properties.EmbedInteropTypes). Select((res) => res.Reference)); parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single()); Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference); parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c")); parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1")); parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:")); parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R")); parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+")); parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:")); } [Fact] public void Target_SimpleTests() { var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t")); parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget)); parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+")); parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:")); } [Fact] public void Target_SimpleTestsNoSource() { var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind); parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/t' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module' Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/T+' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/TARGET-:' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1), // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)); } [Fact] public void ModuleManifest() { CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory); args.Errors.Verify( // warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies Diagnostic(ErrorCode.WRN_CantHaveManifestForModule)); // Illegal, but not clobbered. Assert.Equal("blah", args.Win32Manifest); } [Fact] public void ArgumentParsing() { var sdkDirectory = SdkDirectory; var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayLangVersions); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2001: Source file '//langversion:?' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1) ); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayVersion); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1)); Assert.False(parsedArgs.DisplayHelp); Assert.Equal(1, parsedArgs.SourceFiles.Length); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd' Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file"))); Assert.False(parsedArgs.DisplayHelp); Assert.False(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/define:goo' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo")); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.DisplayHelp); Assert.True(parsedArgs.SourceFiles.Any()); } [Theory] [InlineData("iso-1", LanguageVersion.CSharp1)] [InlineData("iso-2", LanguageVersion.CSharp2)] [InlineData("1", LanguageVersion.CSharp1)] [InlineData("1.0", LanguageVersion.CSharp1)] [InlineData("2", LanguageVersion.CSharp2)] [InlineData("2.0", LanguageVersion.CSharp2)] [InlineData("3", LanguageVersion.CSharp3)] [InlineData("3.0", LanguageVersion.CSharp3)] [InlineData("4", LanguageVersion.CSharp4)] [InlineData("4.0", LanguageVersion.CSharp4)] [InlineData("5", LanguageVersion.CSharp5)] [InlineData("5.0", LanguageVersion.CSharp5)] [InlineData("6", LanguageVersion.CSharp6)] [InlineData("6.0", LanguageVersion.CSharp6)] [InlineData("7", LanguageVersion.CSharp7)] [InlineData("7.0", LanguageVersion.CSharp7)] [InlineData("7.1", LanguageVersion.CSharp7_1)] [InlineData("7.2", LanguageVersion.CSharp7_2)] [InlineData("7.3", LanguageVersion.CSharp7_3)] [InlineData("8", LanguageVersion.CSharp8)] [InlineData("8.0", LanguageVersion.CSharp8)] [InlineData("9", LanguageVersion.CSharp9)] [InlineData("9.0", LanguageVersion.CSharp9)] [InlineData("preview", LanguageVersion.Preview)] public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory); scriptParsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion); Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("6", "7", LanguageVersion.CSharp7)] [InlineData("7", "6", LanguageVersion.CSharp6)] [InlineData("7", "1", LanguageVersion.CSharp1)] [InlineData("6", "iso-1", LanguageVersion.CSharp1)] [InlineData("6", "iso-2", LanguageVersion.CSharp2)] [InlineData("6", "default", LanguageVersion.Default)] [InlineData("7", "default", LanguageVersion.Default)] [InlineData("iso-2", "6", LanguageVersion.CSharp6)] public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion) { var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Fact] public void LangVersion_DefaultMapsCorrectly() { LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_LatestMapsCorrectly() { LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion); var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion); Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion); } [Fact] public void LangVersion_NoValueSpecified() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion); } [Theory] [InlineData("iso-3")] [InlineData("iso1")] [InlineData("8.1")] [InlineData("10.1")] [InlineData("11")] [InlineData("1000")] public void LangVersion_BadVersion(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1) ); } [Theory] [InlineData("0")] [InlineData("05")] [InlineData("07")] [InlineData("07.1")] [InlineData("08")] [InlineData("09")] public void LangVersion_LeadingZeroes(string value) { DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS8303: Specified language version 'XXX' cannot have leading zeroes Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1)); } [Theory] [InlineData("/langversion")] [InlineData("/langversion:")] [InlineData("/LANGversion:")] public void LangVersion_NoVersion(string option) { DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1)); } [Fact] public void LangVersion_LangVersions() { var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory); args.Errors.Verify( // warning CS2008: No source files specified. Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1), // error CS1562: Outputs without source must have the /out option specified Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1) ); Assert.True(args.DisplayLangVersions); } [Fact] public void LanguageVersionAdded_Canary() { // When a new version is added, this test will break. This list must be checked: // - update the "UpgradeProject" codefixer // - update all the tests that call this canary // - update MaxSupportedLangVersion (a relevant test should break when new version is introduced) // - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454) AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" }, Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString())); // For minor versions and new major versions, the format should be "x.y", such as "7.1" } [Fact] public void LanguageVersion_GetErrorCode() { var versions = Enum.GetValues(typeof(LanguageVersion)) .Cast<LanguageVersion>() .Except(new[] { LanguageVersion.Default, LanguageVersion.Latest, LanguageVersion.LatestMajor, LanguageVersion.Preview }) .Select(v => v.GetErrorCode()); var errorCodes = new[] { ErrorCode.ERR_FeatureNotAvailableInVersion1, ErrorCode.ERR_FeatureNotAvailableInVersion2, ErrorCode.ERR_FeatureNotAvailableInVersion3, ErrorCode.ERR_FeatureNotAvailableInVersion4, ErrorCode.ERR_FeatureNotAvailableInVersion5, ErrorCode.ERR_FeatureNotAvailableInVersion6, ErrorCode.ERR_FeatureNotAvailableInVersion7, ErrorCode.ERR_FeatureNotAvailableInVersion7_1, ErrorCode.ERR_FeatureNotAvailableInVersion7_2, ErrorCode.ERR_FeatureNotAvailableInVersion7_3, ErrorCode.ERR_FeatureNotAvailableInVersion8, ErrorCode.ERR_FeatureNotAvailableInVersion9, ErrorCode.ERR_FeatureNotAvailableInVersion10, }; AssertEx.SetEqual(versions, errorCodes); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1), InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2), InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3), InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4), InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5), InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6), InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7), InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1), InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2), InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3), InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8), InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9), InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10), InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor), InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest), InlineData(LanguageVersion.CSharp10, LanguageVersion.Default), InlineData(LanguageVersion.Preview, LanguageVersion.Preview), ] public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input) { Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion()); Assert.True(expectedMappedVersion.IsValid()); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Theory, InlineData("iso-1", true, LanguageVersion.CSharp1), InlineData("ISO-1", true, LanguageVersion.CSharp1), InlineData("iso-2", true, LanguageVersion.CSharp2), InlineData("1", true, LanguageVersion.CSharp1), InlineData("1.0", true, LanguageVersion.CSharp1), InlineData("2", true, LanguageVersion.CSharp2), InlineData("2.0", true, LanguageVersion.CSharp2), InlineData("3", true, LanguageVersion.CSharp3), InlineData("3.0", true, LanguageVersion.CSharp3), InlineData("4", true, LanguageVersion.CSharp4), InlineData("4.0", true, LanguageVersion.CSharp4), InlineData("5", true, LanguageVersion.CSharp5), InlineData("5.0", true, LanguageVersion.CSharp5), InlineData("05", false, LanguageVersion.Default), InlineData("6", true, LanguageVersion.CSharp6), InlineData("6.0", true, LanguageVersion.CSharp6), InlineData("7", true, LanguageVersion.CSharp7), InlineData("7.0", true, LanguageVersion.CSharp7), InlineData("07", false, LanguageVersion.Default), InlineData("7.1", true, LanguageVersion.CSharp7_1), InlineData("7.2", true, LanguageVersion.CSharp7_2), InlineData("7.3", true, LanguageVersion.CSharp7_3), InlineData("8", true, LanguageVersion.CSharp8), InlineData("8.0", true, LanguageVersion.CSharp8), InlineData("9", true, LanguageVersion.CSharp9), InlineData("9.0", true, LanguageVersion.CSharp9), InlineData("10", true, LanguageVersion.CSharp10), InlineData("10.0", true, LanguageVersion.CSharp10), InlineData("08", false, LanguageVersion.Default), InlineData("07.1", false, LanguageVersion.Default), InlineData("default", true, LanguageVersion.Default), InlineData("latest", true, LanguageVersion.Latest), InlineData("latestmajor", true, LanguageVersion.LatestMajor), InlineData("preview", true, LanguageVersion.Preview), InlineData("latestpreview", false, LanguageVersion.Default), InlineData(null, true, LanguageVersion.Default), InlineData("bad", false, LanguageVersion.Default)] public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected) { Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version)); Assert.Equal(expected, version); // The canary check is a reminder that this test needs to be updated when a language version is added LanguageVersionAdded_Canary(); } [Fact] public void LanguageVersion_TryParseTurkishDisplayString() { var originalCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false); Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version)); Assert.Equal(LanguageVersion.CSharp1, version); Thread.CurrentThread.CurrentCulture = originalCulture; } [Fact] public void LangVersion_ListLangVersions() { var dir = Temp.CreateDirectory(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>() .Select(v => v.ToDisplayString()); var actual = outWriter.ToString(); var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' }; foreach (var version in expected) { if (version == "latest") continue; var foundIndex = actual.IndexOf(version); Assert.True(foundIndex > 0, $"Missing version '{version}'"); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0); Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0); } } [Fact] [WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")] public void Define() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory); Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.False(parsedArgs.Errors.Any()); parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count()); Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code); Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]); IEnumerable<Diagnostic> diagnostics; // The docs say /d:def1[;def2] string compliant = "def1;def2;def3"; var expected = new[] { "def1", "def2", "def3" }; var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // Bug 17360: Dev11 allows for a terminating semicolon var dev11Compliant = "def1;def2;def3;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // And comma dev11Compliant = "def1,def2,def3,"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics); diagnostics.Verify(); Assert.Equal<string>(expected, parsed); // This breaks everything var nonCompliant = "def1;;def2;"; parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics); diagnostics.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("")); Assert.Equal(new[] { "def1", "def2" }, parsed); // Bug 17360 parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Fact] public void Debug() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.False(parsedArgs.EmitPdbFile); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.DebugPlusMode); Assert.True(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.DebugPlusMode); Assert.False(parsedArgs.EmitPdb); Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat); parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug")); parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+")); parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid")); parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:")); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void Pdb() { var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath); Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll")); Assert.False(parsedArgs.EmitPdbFile); parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.PdbPath); Assert.True(parsedArgs.EmitPdbFile); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb")); Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll")); parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:")); parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // temp: path changed //parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/pdb:""' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Temp: Path info changed // Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath); // invalid name: parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb")); Assert.Null(parsedArgs.PdbPath); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb")); Assert.Null(parsedArgs.PdbPath); parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.PdbPath); } [Fact] public void SourceLink() { var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb)); } [Fact] public void SourceLink_EndToEnd_EmbeddedPortable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe")); using (var peReader = new PEReader(peStream)) { var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Portable() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); sl.WriteAllText(@"{ ""documents"" : {} }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)) { var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob(); AssertEx.Equal(File.ReadAllBytes(sl.Path), blob); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void SourceLink_EndToEnd_Windows() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() {} }"); var sl = dir.CreateFile("sl.json"); byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }"); sl.WriteAllBytes(slContent); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb")); var actualData = PdbValidation.GetSourceLinkData(pdbStream); AssertEx.Equal(slContent, actualData); // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Fact] public void Embed() { var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Empty(parsedArgs.EmbeddedFiles); parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles); AssertEx.Equal( new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal( new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); ; AssertEx.Equal( new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)), parsedArgs.EmbeddedFiles.Select(f => f.Path)); parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb)); parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } [Theory] [InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })] [InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })] [InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })] [InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })] public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded) { // embed.cs: large enough to compress, has #line directives const string embed_cs = @"/////////////////////////////////////////////////////////////////////////////// class Program { static void Main() { #line 1 ""embed.xyz"" System.Console.WriteLine(""Hello, World""); #line 3 System.Console.WriteLine(""Goodbye, World""); } } ///////////////////////////////////////////////////////////////////////////////"; // embed2.cs: small enough to not compress, no sequence points const string embed2_cs = @"class C { }"; // target of #line const string embed_xyz = @"print Hello, World print Goodbye, World"; Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold); Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("embed.cs"); var src2 = dir.CreateFile("embed2.cs"); var txt = dir.CreateFile("embed.xyz"); src.WriteAllText(embed_cs); src2.WriteAllText(embed2_cs); txt.WriteAllText(embed_xyz); var expectedEmbeddedMap = new Dictionary<string, string>(); if (expectedEmbedded.Contains("embed.cs")) { expectedEmbeddedMap.Add(src.Path, embed_cs); } if (expectedEmbedded.Contains("embed2.cs")) { expectedEmbeddedMap.Add(src2.Path, embed2_cs); } if (expectedEmbedded.Contains("embed.xyz")) { expectedEmbeddedMap.Add(txt.Path, embed_xyz); } var output = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" }); int exitCode = csc.Run(output); Assert.Equal("", output.ToString().Trim()); Assert.Equal(0, exitCode); switch (debugSwitch) { case "/debug:embedded": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true); break; case "/debug:portable": ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false); break; case "/debug:full": ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir); break; } Assert.Empty(expectedEmbeddedMap); CleanupAllGeneratedFiles(src.Path); } private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb) { using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe")))) { var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); Assert.Equal(isEmbeddedPdb, entry.DataSize > 0); using (var mdProvider = isEmbeddedPdb ? peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) : MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")))) { var mdReader = mdProvider.GetMetadataReader(); foreach (var handle in mdReader.Documents) { var doc = mdReader.GetDocument(handle); var docPath = mdReader.GetString(doc.Name); SourceText embeddedSource = mdReader.GetEmbeddedSource(handle); if (embeddedSource == null) { continue; } Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString()); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } } } private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir) { ISymUnmanagedReader5 symReader = null; try { symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))); foreach (var doc in symReader.GetDocuments()) { var docPath = doc.GetName(); var sourceBlob = doc.GetEmbeddedSource(); if (sourceBlob.Array == null) { continue; } var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count); Assert.Equal(expectedEmbeddedMap[docPath], sourceStr); Assert.True(expectedEmbeddedMap.Remove(docPath)); } } catch { symReader?.Dispose(); } } private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null) { foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray()) { foreach (var file in Directory.GetFiles(dirPath)) { var name = Path.GetFileName(file); var content = File.ReadAllText(file, encoding ?? Encoding.UTF8); Assert.Equal(fileMap[name], content); Assert.True(fileMap.Remove(name)); } Assert.Empty(fileMap); Assert.True(expectedFilesMap.Remove(dirPath)); } Assert.Empty(expectedFilesMap); } [Fact] public void Optimize() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+")); parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:")); parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:")); parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory); Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel); parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+")); parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:")); parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:")); } [Fact] public void Deterministic() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.Deterministic); parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.Deterministic); } [Fact] public void ParseReferences() { var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties); parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(4, parsedArgs.MetadataReferences.Length); Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties); Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties); Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties); Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference); Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties); // TODO: multiple files, quotes, etc. } [Fact] public void ParseAnalyzers() { var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(2, parsedArgs.AnalyzerReferences.Length); Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath); Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath); parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:")); parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a")); } [Fact] public void Analyzers_Missing() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_Empty() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.DoesNotContain("warning", outWriter.ToString()); CleanupAllGeneratedFiles(file.Path); } private TempFile CreateRuleSetFile(string source) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.ruleset"); file.WriteAllText(source); return file; } [Fact] public void RuleSetSwitchPositive() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014")); Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress); Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn); } [Fact] public void RuleSetSwitchQuoted() { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> <Rule Id=""CA1013"" Action=""Warning"" /> <Rule Id=""CA1014"" Action=""None"" /> </Rules> </RuleSet> "; var file = CreateRuleSetFile(source); var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); } [Fact] public void RuleSetSwitchParseErrors() { var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset")); Assert.Null(parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath); parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found.")); Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath); var file = CreateRuleSetFile("Random text"); parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory); //parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1.")); Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath); var err = parsedArgs.Errors.Single(); Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal(file.Path, (string)err.Arguments[0]); var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name; if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase)) { Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]); } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void Analyzers_Found() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic thrown Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared")); // Diagnostic cannot be instantiated Assert.True(outWriter.ToString().Contains("warning CS8032")); CleanupAllGeneratedFiles(file.Path); } [Fact] public void Analyzers_WithRuleSet() { string source = @" class C { int x; } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error. Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared")); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // Diagnostic thrown as error: command line always overrides ruleset. Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Info"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_GeneralWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusResetsRules() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/warnaserror-:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+:Test002", "/warnaserror-:Test002", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn); Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesRuleSet() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/warnaserror+", "/nowarn:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError() { var dir = Temp.CreateDirectory(); string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Test001"" Action=""Warning"" /> </Rules> </RuleSet> "; var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/ruleset:Rules.ruleset", "/nowarn:Test001", "/warnaserror+:Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_Capitalization() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:NullABLE", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void NoWarn_Nullable_MultipleArguments() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/nowarn:nullable,Test001", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [Fact] [WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void WarnAsError_Nullable() { var dir = Temp.CreateDirectory(); var arguments = DefaultParse( new[] { "/nologo", "/t:library", "/warnaserror:nullable", "a.cs" }, dir.Path); var errors = arguments.Errors; Assert.Empty(errors); Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count); foreach (string warning in ErrorFacts.NullableWarnings) { Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]); } Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]); Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]); } [WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")] [Fact] public void Analyzers_CommandLineOverridesRuleset2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""Warning01"" Action=""Error"" /> </Rules> </RuleSet> "; var ruleSetFile = CreateRuleSetFile(rulesetSource); var outWriter = new StringWriter(CultureInfo.InvariantCulture); // This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation. var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path, "/warn:0" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/warn:0", "/ruleset:" + ruleSetFile.Path }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); // Diagnostic suppressed: commandline always overrides ruleset. Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal); // Clean up temp files CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void DiagnosticFormatting() { string source = @" using System; class C { public static void Main() { Goo(0); #line 10 ""c:\temp\a\1.cs"" Goo(1); #line 20 ""C:\a\..\b.cs"" Goo(2); #line 30 ""C:\a\../B.cs"" Goo(3); #line 40 ""../b.cs"" Goo(4); #line 50 ""..\b.cs"" Goo(5); #line 60 ""C:\X.cs"" Goo(6); #line 70 ""C:\x.cs"" Goo(7); #line 90 "" "" Goo(9); #line 100 ""C:\*.cs"" Goo(10); #line 110 """" Goo(11); #line hidden Goo(12); #line default Goo(13); #line 140 ""***"" Goo(14); } } "; var dir = Temp.CreateDirectory(); dir.CreateFile("a.cs").WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); // with /fullpaths off string expected = @" a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); // with /fullpaths on outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" }); exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); expected = @" " + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context (90,7): error CS0103: The name 'Goo' does not exist in the current context C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context (110,7): error CS0103: The name 'Goo' does not exist in the current context (112,13): error CS0103: The name 'Goo' does not exist in the current context " + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context ***(140,13): error CS0103: The name 'Goo' does not exist in the current context"; AssertEx.Equal( expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), itemSeparator: "\r\n"); } [WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseOut() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("")); parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:")); parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/refout:' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:")); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8301: Do not use refout when using refonly. Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/refonly:incorrect' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS8302: Cannot compile net modules when using /refout or /refonly. Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1) ); // Dev11 reports CS2007: Unrecognized option: '/out' parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for '/out' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out")); parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+")); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory); Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName)); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("MyBinary", parsedArgs.CompilationName); Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName); Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory); // not specified: exe parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: dll parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.dll", parsedArgs.OutputFileName); Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: module parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: appcontainerexe parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // not specified: winmdobj parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationName); Assert.Equal("a.winmdobj", parsedArgs.OutputFileName); Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs")); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); Assert.Equal(baseDirectory, parsedArgs.OutputDirectory); // UNC parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory); Assert.Equal("file.exe", parsedArgs.OutputFileName); Assert.Equal("file", parsedArgs.CompilationName); Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName); // invalid name: parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); // Temporary skip following scenarios because of the error message changed (path) //parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory); //parsedArgs.Errors.Verify( // // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll")); // Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z' parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll") ); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(".netmodule", parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName); } [WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")] [WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")] [Fact] public void ParseOut2() { var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x")); Assert.Null(parsedArgs.OutputFileName); Assert.Null(parsedArgs.CompilationName); Assert.Null(parsedArgs.CompilationOptions.ModuleName); } [Fact] public void ParseInstrumentTestNames() { var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty)); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption")); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseDoc() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:")); Assert.Null(parsedArgs.DocumentationPath); // NOTE: no colon in error message '/doc' parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc")); Assert.Null(parsedArgs.DocumentationPath); parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+")); Assert.Null(parsedArgs.DocumentationPath); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // UNC parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); // invalid name: parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect // Temp // parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory); // parsedArgs.Errors.Verify( // Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml")); // Assert.Null(parsedArgs.DocumentationPath); // Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.DocumentationPath); Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseErrorLog() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should preserve fully qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Escaped quote in the middle is an error parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1)); // Should handle quotes parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Should expand partially qualified paths parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // drive-relative path: char currentDrive = Directory.GetCurrentDirectory()[0]; parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // UNC parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path); // invalid name: parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml")); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Parses SARIF version. parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion); Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Invalid SARIF version. string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" }; foreach (string invalidSarifVersion in invalidSarifVersions) { parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } // Invalid errorlog qualifier. const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42"; parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); // Too many errorlog qualifiers. const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2"; parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'. Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat)); Assert.Null(parsedArgs.ErrorLogOptions); Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigParse() { const string baseDirectory = @"C:\abc\def\baz"; var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig")); Assert.Null(parsedArgs.AppConfigPath); parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath); // If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath } [Fact] public void AppConfigBasic() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var appConfigFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>"); var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path; var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path; // Test linking two appconfig dlls with simple src var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/r:" + silverlight, "/r:" + net4_0dll, "/appconfig:" + appConfigFile.Path, srcFile.Path }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(appConfigFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void AppConfigBasicFail() { var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready' var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, srcDirectory, new[] { "/nologo", "/preferreduilang:en", $@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" , srcFile.Path }).Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(srcFile.Path); } [ConditionalFact(typeof(WindowsOnly))] public void ParseDocAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and XML output. var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [ConditionalFact(typeof(WindowsOnly))] public void ParseErrorLogAndOut() { const string baseDirectory = @"C:\abc\def\baz"; // Can specify separate directories for binary and error log output. var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); // XML does not fall back on output directory. parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path); Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory); Assert.Equal("d.exe", parsedArgs.OutputFileName); } [Fact] public void ModuleAssemblyName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationName); Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module' Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule)); } [Fact] public void ModuleName() { var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName); parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1) ); } [Fact] public void ModuleName001() { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile("a.cs"); file1.WriteAllText(@" class c1 { public static void Main(){} } "); var exeName = "aa.exe"; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path }); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe")))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(exeName)) { System.IO.File.Delete(exeName); } CleanupAllGeneratedFiles(file1.Path); } [Fact] public void ParsePlatform() { var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform); parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:")); Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default } [WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")] [WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")] [WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")] [WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")] [Fact] public void ParseBaseAddress() { var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory); Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF")); parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000")); parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000")); } [Fact] public void ParseFileAlignment() { var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number 'x64' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64")); parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign")); parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '-23' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23")); parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment); parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '0' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0")); parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2024: Invalid file section alignment number '123' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123")); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable() { var dir = Temp.CreateDirectory(); var lib1 = dir.CreateDirectory("lib1"); var lib2 = dir.CreateDirectory("lib2"); var lib3 = dir.CreateDirectory("lib3"); var sdkDirectory = SdkDirectory; var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory); AssertEx.Equal(new[] { sdkDirectory, lib1.Path, lib2.Path, lib3.Path }, parsedArgs.ReferencePaths); } [ConditionalFact(typeof(WindowsOnly))] public void SdkPathAndLibEnvVariable_Errors() { var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist")); parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"), // warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"), // warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid")); parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+")); parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib")); } [Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")] public void SdkPathAndLibEnvVariable_Relative_csc() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var subDirectory = subFolder.ToString(); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } [Fact] public void UnableWriteOutput() { var tempFolder = Temp.CreateDirectory(); var baseDirectory = tempFolder.ToString(); var subFolder = tempFolder.CreateDirectory("temp"); var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists. CleanupAllGeneratedFiles(src.Path); } [Fact] public void ParseHighEntropyVA() { var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); //last one wins parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.Errors.Any()); Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace); } [Fact] public void Checked() { var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.CheckOverflow); parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:")); } [Fact] public void Nullable() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1), // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1) ); Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions); } [Fact] public void Usings() { CSharpCommandLineArguments parsedArgs; var sdkDirectory = SdkDirectory; parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify(); AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable()); parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:")); } [Fact] public void WarningsErrors() { var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn")); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror")); parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+")); parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-")); parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w")); parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1900: Warning level must be zero or greater Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn")); parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied via /nowarn or /warnaserror. // We no longer generate a warning in such cases. parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); } private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args) { var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key); AssertEx.Equal( expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)), actualOrdered.Select(entry => entry.Key)); AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value)); } [Fact] public void WarningsParse() { var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics( new[] { 1062, 1066, 1734, 1762, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs); parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption); Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel); AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs); } [Fact] public void AllowUnsafe() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.AllowUnsafe); parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:")); parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+")); parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:")); } [Fact] public void DelaySign() { CSharpCommandLineArguments parsedArgs; parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.True((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.NotNull(parsedArgs.CompilationOptions.DelaySign); Assert.False((bool)parsedArgs.CompilationOptions.DelaySign); parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/delaysign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-")); Assert.Null(parsedArgs.CompilationOptions.DelaySign); } [Fact] public void PublicSign() { var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.CompilationOptions.PublicSign); parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/publicsign:-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1)); Assert.False(parsedArgs.CompilationOptions.PublicSign); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [Fact] public void PublicSign_KeyFileRelativePath() { var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1)); } [WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")] [Fact] public void SubsystemVersionTests() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion); // wrongly supported subsystem version. CompilationOptions data will be faithful to the user input. // It is normalized at the time of emit. parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); // no error in Dev11 Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion); parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-")); parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion")); parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.")); parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536")); parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0")); parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0")); // TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer' } [Fact] public void MainType() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName); parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11 parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); Assert.Null(parsedArgs.CompilationOptions.MainTypeName); // overriding the value parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName); // error parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main")); parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+")); parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m")); // incompatible values /main && /target parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL)); } [Fact] public void Codepage() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName); parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName); // error parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0")); parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc")); parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5")); parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("")); parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage")); parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+")); } [Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")] public void ChecksumAlgorithm() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm); Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm); // error parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm")); parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+")); } [Fact] public void AddModule() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(1, parsedArgs.MetadataReferences.Length); Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(3, parsedArgs.MetadataReferences.Length); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind); Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind); Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference); Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind); // error parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:")); parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+")); parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:")); } [Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")] public void CS7061fromCS0647_ModuleWithCompilationRelaxations() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] public class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(4)] public class Mod { }").Path; string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] class Test { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source); // === Scenario 1 === var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Empty(outWriter.ToString()); // === Scenario 2 === outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter); Assert.Equal(0, exitCode); modfile = source2.Substring(0, source2.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory); parsedArgs.Errors.Verify(); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter); Assert.Equal(1, exitCode); // Dev11: CS0647 (Emit) Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")] public void AddModuleWithExtensionMethod() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")] public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes() { string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path; string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path; var baseDir = Path.GetDirectoryName(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter); Assert.Equal(0, exitCode); var modfile = source1.Substring(0, source1.Length - 2) + "netmodule"; outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter); Assert.Equal(1, exitCode); // Native gives CS0013 at emit stage Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source1); CleanupAllGeneratedFiles(source2); } [Fact] public void Utf8Output() { CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True((bool)parsedArgs.Utf8Output); parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:")); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) : ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir); Assert.Equal("Hello World!", output.Trim()); } [Fact] public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary() { var name = Guid.NewGuid().ToString() + ".dll"; string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public A Get() =^^^> default; ^ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -" .Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public A Get\(\) =\> default\; \ }} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name)); Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), assemblyName.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")] public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}"); Assert.Equal("Hello World!", result.Output.Trim()); } [Fact] public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782() { if (Console.IsInputRedirected) { // [applicable to both Windows and Unix] // if our parent (xunit) process itself has input redirected, we cannot test this // error case because our child process will inherit it and we cannot achieve what // we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in // child. running this case will make StreamReader to hang (waiting for input, that // we do not propagate: parent.In->child.In). // // note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below, // but that will also not impact the result of isatty(), and in turn causes a different // compiler error. return; } string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir); Assert.True(result.ContainsErrors); Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output); } [Fact] public void CscCompile_WithMultipleStdInOperators_WarnsCS2002() { string tempDir = Temp.CreateDirectory().Path; ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ProcessUtilities.Run("cmd", $@"/C echo ^ class A ^ {{ ^ public static void Main() =^^^> ^ System.Console.WriteLine(""Hello World!""); ^ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -" .Replace(Environment.NewLine, string.Empty)) : ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \ class A \ {{ \ public static void Main\(\) =\> \ System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \ }} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir, // we are testing shell's piped/redirected stdin behavior explicitly // instead of using Process.StandardInput.Write(), so we set // redirectStandardInput to true, which implies that isatty of child // process is false and thereby Console.IsInputRedirected will return // true in csc code. redirectStandardInput: true); Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_Off() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void CscUtf8Output_WithRedirecting_On() { var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path; var tempOut = Temp.CreateFile(); var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1); Assert.Equal("", output.Trim()); Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS")); CleanupAllGeneratedFiles(srcFile); CleanupAllGeneratedFiles(tempOut.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithModule() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString()); Assert.Equal("warning CS2008: No source files specified.", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void NoSourcesWithLinkResource() { var folder = Temp.CreateDirectory(); var aCs = folder.CreateFile("a.cs"); aCs.WriteAllText("public class C {}"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString()); Assert.Equal("", output.Trim()); CleanupAllGeneratedFiles(aCs.Path); } [Fact] public void KeyContainerAndKeyFile() { // KEYCONTAINER CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keycontainer-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); //EDMAURER let's not set the option in the event that there was an error. //Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2005: Missing file specification for 'keyfile' option Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS2007: Unrecognized option: '/keyfile-' Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-")); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); // DEFAULTS parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer); // KEYFILE | KEYCONTAINER conflicts parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile); Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer); } [Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")] public void CS1698WRN_AssumedMatchThis() { // compile with: /target:library /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")] public class CS1698_a {} "; // compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk var text2 = @"public class CS1698_b : CS1698_a {} "; //compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")] public class CS1698_c : CS1698_b {} public class CS1698_a {} "; var folder = Temp.CreateDirectory(); var cs1698a = folder.CreateFile("CS1698a.cs"); cs1698a.WriteAllText(text1); var cs1698b = folder.CreateFile("CS1698b.cs"); cs1698b.WriteAllText(text2); var cs1698 = folder.CreateFile("CS1698.cs"); cs1698.WriteAllText(text); var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var kfile = "/keyfile:" + snkFile.Path; CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory); // Roslyn no longer generates a warning for this...since this was only a warning, we're not really // saving anyone...does not provide high value to implement... // warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10' // does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'. // Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match. parsedArgs.Errors.Verify(); CleanupAllGeneratedFiles(snkFile.Path); CleanupAllGeneratedFiles(cs1698a.Path); CleanupAllGeneratedFiles(cs1698b.Path); CleanupAllGeneratedFiles(cs1698.Path); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path; var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( "error CS2015: '" + binaryPath + "' is a binary file instead of a text file", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(binaryPath); } #if !NETCOREAPP [WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")] [WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")] [ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))] public void Bug15538() { // Several Jenkins VMs are still running with local systems permissions. This suite won't run properly // in that environment. Removing this check is being tracked by issue #79. using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent()) { if (identity.IsSystem) { return; } // The icacls command fails on our Helix machines and it appears to be related to the use of the $ in // the username. // https://github.com/dotnet/roslyn/issues/28836 if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP")) { return; } } var folder = Temp.CreateDirectory(); var source = folder.CreateFile("src.vb").WriteAllText("").Path; var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path; try { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1); Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim()); } finally { var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q"); Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim()); File.Delete(_ref); } CleanupAllGeneratedFiles(source); } #endif [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="""" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileOrdering() { var rspFilePath1 = Temp.CreateFile().WriteAllText(@" /b /c ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d" }, new[] { "/a", @$"@""{rspFilePath1}""", "/d" }); var rspFilePath2 = Temp.CreateFile().WriteAllText(@" /c /d ").Path; rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b @""{rspFilePath2}"" ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", "/e" }); rspFilePath1 = Temp.CreateFile().WriteAllText(@$" /b ").Path; rspFilePath2 = Temp.CreateFile().WriteAllText(@" # this will be ignored /c /d ").Path; assertOrder( new[] { "/a", "/b", "/c", "/d", "/e" }, new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" }); void assertOrder(string[] expected, string[] args) { var flattenedArgs = ArrayBuilder<string>.GetInstance(); var diagnostics = new List<Diagnostic>(); CSharpCommandLineParser.Default.FlattenArgs( args, diagnostics, flattenedArgs, scriptArgsOpt: null, baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/"); Assert.Empty(diagnostics); Assert.Equal(expected, flattenedArgs); flattenedArgs.Free(); } } [WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")] [Fact] public void ResponseFilesWithEmptyAliasReference2() { string source = Temp.CreateFile("a.cs").WriteAllText(@" // <Area> ExternAlias - command line alias</Area> // <Title> // negative test cases: empty file name ("""") // </Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=error>CS1680:.*myAlias=</Expects> // <Code> class myClass { static int Main() { return 1; } } // </Code> ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /nologo /r:myAlias="" "" ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFile() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"" /d:""AA;BB"" /d:""N""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")] [Fact] public void QuotedDefineInRespFileErr() { string source = Temp.CreateFile("a.cs").WriteAllText(@" #if NN class myClass { #endif static int Main() #if DD { return 1; #endif #if AA } #endif #if BB } #endif ").Path; string rsp = Temp.CreateFile().WriteAllText(@" /d:""DD"""" /d:""AA;BB"" /d:""N"" ""N ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact] public void ResponseFileSplitting() { string[] responseFile; responseFile = new string[] { @"a.cs b.cs ""c.cs e.cs""", @"hello world # this is a comment" }; IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args); // Check comment handling; comment character only counts at beginning of argument responseFile = new string[] { @" # ignore this", @" # ignore that ""hello""", @" a.cs #3.cs", @" b#.cs c#d.cs #e.cs", @" ""#f.cs""", @" ""#g.cs #h.cs""" }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args); // Check backslash escaping responseFile = new string[] { @"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args); // More backslash escaping and quoting responseFile = new string[] { @"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args); // Quoting inside argument is valid. responseFile = new string[] { @" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing", }; args = CSharpCommandLineParser.ParseResponseLines(responseFile); AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args); } [ConditionalFact(typeof(WindowsOnly))] private void SourceFileQuoting() { string[] responseFile = new string[] { @"d:\\""abc def""\baz.cs ab""c d""e.cs", }; CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\"); AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path)); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName1() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since DLL. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library" }, expectedOutputName: "p.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName2() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:library", "/out:r.dll" }, expectedOutputName: "r.dll"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName3() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName4() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from command-line option. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName5() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:A" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName6() { string source1 = @" class A { static void Main() { } } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint - affected by /main, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/main:B" }, expectedOutputName: "q.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName7() { string source1 = @" partial class A { static partial void Main() { } } "; string source2 = @" partial class A { static partial void Main(); } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "p.exe"); } [WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")] [Fact] public void OutputFileName8() { string source1 = @" partial class A { static partial void Main(); } "; string source2 = @" partial class A { static partial void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName9() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from first input (file, not class) name, since winmdobj. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:winmdobj" }, expectedOutputName: "p.winmdobj"); } [Fact] public void OutputFileName10() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since appcontainerexe. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:appcontainerexe" }, expectedOutputName: "q.exe"); } [Fact] public void OutputFileName_Switch() { string source1 = @" class A { } "; string source2 = @" class B { static void Main() { } } "; // Name comes from name of file containing entrypoint, since EXE. CheckOutputFileName( source1, source2, inputName1: "p.cs", inputName2: "q.cs", commandLineArguments: new[] { "/target:exe", "/out:r.exe" }, expectedOutputName: "r.exe"); } [Fact] public void OutputFileName_NoEntryPoint() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")] public void VerifyDiagnosticSeverityNotLocalized() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); // If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:" Assert.Contains("error CS5001:", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_1() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(@"", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [Fact] public void NoLogo_2() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d"); patched = ReplaceCommitHash(patched); Assert.Equal(@" Microsoft (R) Visual C# Compiler version A.B.C-d (HASH) Copyright (C) Microsoft Corporation. All rights reserved.".Trim(), patched); CleanupAllGeneratedFiles(file.Path); } [Theory, InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"), InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)", "Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")] public void TestReplaceCommitHash(string orig, string expected) { Assert.Equal(expected, ReplaceCommitHash(orig)); } private static string ReplaceCommitHash(string s) { // open paren, followed by either <developer build> or 8 hex, followed by close paren return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)"); } [Fact] public void ExtractShortCommitHash() { Assert.Null(CommonCompiler.ExtractShortCommitHash(null)); Assert.Equal("", CommonCompiler.ExtractShortCommitHash("")); Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<")); Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>")); Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1")); Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678")); Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789")); } private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName) { var dir = Temp.CreateDirectory(); var file1 = dir.CreateFile(inputName1); file1.WriteAllText(source1); var file2 = dir.CreateFile(inputName2); file2.WriteAllText(source2); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray()); int exitCode = csc.Run(outWriter); if (exitCode != 0) { Console.WriteLine(outWriter.ToString()); Assert.Equal(0, exitCode); } Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count()); Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count()); using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName)))) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name)); } if (System.IO.File.Exists(expectedOutputName)) { System.IO.File.Delete(expectedOutputName); } CleanupAllGeneratedFiles(file1.Path); CleanupAllGeneratedFiles(file2.Path); } [Fact] public void MissingReference() { string source = @" class C { } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_01() { string source = @" public class C { public static void Main() { } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect to be success, since there will be no warning) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:1 (expect success) // Note that even though the command line option has a warning, it is not going to become an error // in order to avoid the halt of compilation. exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" }); Assert.Equal(0, exitCode); } [WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithWarnAsError_02() { string source = @" public class C { public static void Main() { int x; // CS0168 } }"; // Baseline without warning options (expect success) int exitCode = GetExitCode(source, "a.cs", new String[] { }); Assert.Equal(0, exitCode); // The case with /warnaserror (expect failure) exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:168 (expect failure) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" }); Assert.NotEqual(0, exitCode); // The case with /warnaserror:219 (expect success) exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" }); Assert.Equal(0, exitCode); // The case with /warnaserror and /nowarn:168 (expect success) exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" }); Assert.Equal(0, exitCode); } private int GetExitCode(string source, string fileName, string[] commandLineArguments) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray()); int exitCode = csc.Run(outWriter); return exitCode; } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsOnly))] public void CompilationWithNonExistingOutPath() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_01() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_02() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var message = outWriter.ToString(); Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal); Assert.Contains("sub", message, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void CompilationWithWrongOutPath_03() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")] [Fact] public void CompilationWithWrongOutPath_04() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] public void EmittedSubsystemVersion() { var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1)))); Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion); } [Fact] public void CreateCompilationWithKeyFile() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider); } [Fact] public void CreateCompilationWithKeyContainer() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilationFallbackCommand() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" }); var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance); Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType()); } [Fact] public void CreateCompilation_MainAndTargetIncompatibilities() { string source = @" public class C { public static void Main() { } }"; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllText(source); var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll); var options = compilation.Options; Assert.Equal(0, options.Errors.Length); options = options.WithMainTypeName("a"); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); var comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithOutputKind(OutputKind.WindowsApplication); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS1555: Could not find 'a' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a") ); options = options.WithOutputKind(OutputKind.NetModule); options.Errors.Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify( // error CS2017: Cannot specify /main if building a module or library Diagnostic(ErrorCode.ERR_NoMainOnDLL) ); options = options.WithMainTypeName(null); options.Errors.Verify(); comp = CSharpCompilation.Create("a.dll", options: options); comp.GetDiagnostics().Verify(); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void SpecifyProperCodePage() { byte[] source = { 0x63, // c 0x6c, // l 0x61, // a 0x73, // s 0x73, // s 0x20, // 0xd0, 0x96, // Utf-8 Cyrillic character 0x7b, // { 0x7d, // } }; var fileName = "a.cs"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile(fileName); file.WriteAllBytes(source); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path); Assert.Equal("", output); // Autodetected UTF8, NO ERROR output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII // 0xd0, 0x96 ==> ERROR Assert.Equal(@" a.cs(1,7): error CS1001: Identifier expected a.cs(1,7): error CS1514: { expected a.cs(1,7): error CS1513: } expected a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations. a.cs(1,7): error CS1525: Invalid expression term '??' a.cs(1,9): error CS1525: Invalid expression term '{' a.cs(1,9): error CS1002: ; expected ".Trim(), Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim()); CleanupAllGeneratedFiles(file.Path); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForDll() { var source = @" class C { } "; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForAppContainerExe() { var source = @" class C { static void Main() { } } "; CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest: @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""490""> <Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>]]></Contents> </ManifestResource>"); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultManifestForWinMD() { var source = @" class C { } "; CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void DefaultWin32ResForModule() { var source = @" class C { } "; CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null); } [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForExe() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest)); var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest); } // DLLs don't get the default manifest, but they do respect explicitly set manifests. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForDll() { var source = @" class C { static void Main() { } } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; var expectedManifest = @"<?xml version=""1.0"" encoding=""utf-16""?> <ManifestResource Size=""476""> <Contents><![CDATA[" + explicitManifest + @"]]></Contents> </ManifestResource>"; CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest); } // Modules don't have manifests, even if one is explicitly specified. [ConditionalFact(typeof(WindowsOnly))] public void ExplicitWin32ResForModule() { var source = @" class C { } "; var explicitManifest = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> <assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0""> <assemblyIdentity version=""1.0.0.0"" name=""Test.app""/> <trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2""> <security> <requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3""> <requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/> </requestedPrivileges> </security> </trustInfo> </assembly>"; CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null); } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool FreeLibrary([In] IntPtr hFile); private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest) { var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source); string outputFileName; string target; switch (outputKind) { case OutputKind.ConsoleApplication: outputFileName = "Test.exe"; target = "exe"; break; case OutputKind.WindowsApplication: outputFileName = "Test.exe"; target = "winexe"; break; case OutputKind.DynamicallyLinkedLibrary: outputFileName = "Test.dll"; target = "library"; break; case OutputKind.NetModule: outputFileName = "Test.netmodule"; target = "module"; break; case OutputKind.WindowsRuntimeMetadata: outputFileName = "Test.winmdobj"; target = "winmdobj"; break; case OutputKind.WindowsRuntimeApplication: outputFileName = "Test.exe"; target = "appcontainerexe"; break; default: throw TestExceptionUtilities.UnexpectedValue(outputKind); } MockCSharpCompiler csc; if (explicitManifest == null) { csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), Path.GetFileName(sourceFile.Path), }); } else { var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest); csc = CreateCSharpCompiler(null, dir.Path, new[] { string.Format("/target:{0}", target), string.Format("/out:{0}", outputFileName), string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)), Path.GetFileName(sourceFile.Path), }); } int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture)); Assert.Equal(0, actualExitCode); //Open as data IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002); if (lib == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); const string resourceType = "#24"; var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1"; uint manifestSize; if (expectedManifest == null) { Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize)); } else { IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize); string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize); Assert.Equal(expectedManifest, actualManifest); } FreeLibrary(lib); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_01() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { int x; // CS0168 } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /warnaserror ").Path; // Checks the base case without /noconfig (expect to see error) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig (expect to see warning, instead of error) outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_02() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ResponseFilesWithNoconfig_03() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" /NOCONFIG ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")] [ConditionalFact(typeof(WindowsOnly))] public void ResponseFilesWithNoconfig_04() { string source = Temp.CreateFile("a.cs").WriteAllText(@" public class C { public static void Main() { } }").Path; string rsp = Temp.CreateFile().WriteAllText(@" -noconfig ").Path; // Checks the case with /noconfig inside the response file (expect to see warning) var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning) // to verify that this warning is not suppressed by the /nowarn option (See MSDN). outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(rsp); } [Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")] public void NoStdLib() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported", outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim()); // Bug#15021: breaking change - empty source no error with /nostdlib src.WriteAllText("namespace System { }"); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(src.Path); } private string GetDefaultResponseFilePath() { var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp"); return Temp.CreateFile().WriteAllBytes(cscRsp).Path; } [Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")] public void NoStdLib02() { #region "source" var source = @" // <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title> using System.Collections; class O<T> where T : new() { public T list = new T(); } class C { static StructCollection sc = new StructCollection { 1 }; public static int Main() { ClassCollection cc = new ClassCollection { 2 }; var o1 = new O<ClassCollection> { list = { 5 } }; var o2 = new O<StructCollection> { list = sc }; return 0; } } struct StructCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } class ClassCollection : IEnumerable { public int added; #region IEnumerable Members public void Add(int t) { added = t; } #endregion } namespace System.Collections { public interface IEnumerable { void Add(int t); } } "; #endregion #region "mslib" var mslib = @" namespace System { public class Object {} public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { public Exception(string s){} } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } public class Activator { public static T CreateInstance<T>(){return default(T);} } namespace Collections { public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } } "; #endregion var src = Temp.CreateFile("NoStdLib02.cs"); src.WriteAllText(source + mslib); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); string OriginalSource = src.Path; src = Temp.CreateFile("NoStdLib02b.cs"); src.WriteAllText(mslib); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(OriginalSource); CleanupAllGeneratedFiles(src.Path); } [Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")] public void InvalidDefineSwitch() { var src = Temp.CreateFile("a.cs"); src.WriteAllText("public class C{}"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter); Assert.Equal(0, exitCode); var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim()); //Bug 531612 - Native would normally not give the 2nd warning outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter); Assert.Equal(0, exitCode); errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]); Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]); CleanupAllGeneratedFiles(src.Path); } [WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug733242() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml"))); using (var reader = new StreamReader(xmlFileHandle)) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug768605() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC</summary> class C {} /// <summary>XYZ</summary> class E {} "); var xml = dir.CreateFile("a.xml"); xml.WriteAllText("EMPTY"); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> <member name=""T:E""> <summary>XYZ</summary> </member> </members> </doc>".Trim(), content.Trim()); } src.WriteAllText( @" /// <summary>ABC</summary> class C {} "); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); using (var reader = new StreamReader(xml.ToString())) { var content = reader.ReadToEnd(); Assert.Equal( @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""T:C""> <summary>ABC</summary> </member> </members> </doc>".Trim(), content.Trim()); } CleanupAllGeneratedFiles(src.Path); CleanupAllGeneratedFiles(xml.Path); } [Fact] public void ParseFullpaths() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); Assert.False(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory); Assert.True(parsedArgs.PrintFullPaths); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code); } [Fact] public void CheckFullpaths() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public static void Main() { string x; } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); // Checks the base case without /fullpaths (expect to see relative path name) // c:\temp> csc.exe c:\temp\a.cs // a.cs(6,16): warning CS0168: The variable 'x' is declared but never used var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name) // c:\temp> csc.exe c:\temp\example\a.cs // example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the case with /fullpaths (expect to see the full paths) // c:\temp> csc.exe c:\temp\a.cs /fullpaths // c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name) // c:\temp> csc.exe c:\temp\example\a.cs /fullpaths // c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); // Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name) // c:\temp> csc.exe c:\test\a.cs /fullpaths // c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used outWriter = new StringWriter(CultureInfo.InvariantCulture); csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" }); exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source))); } [Fact] public void DefaultResponseFile() { var sdkDirectory = SdkDirectory; MockCSharpCompiler csc = new MockCSharpCompiler( GetDefaultResponseFilePath(), RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory), new string[0]); AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, "Accessibility.dll", "Microsoft.CSharp.dll", "System.Configuration.dll", "System.Configuration.Install.dll", "System.Core.dll", "System.Data.dll", "System.Data.DataSetExtensions.dll", "System.Data.Linq.dll", "System.Data.OracleClient.dll", "System.Deployment.dll", "System.Design.dll", "System.DirectoryServices.dll", "System.dll", "System.Drawing.Design.dll", "System.Drawing.dll", "System.EnterpriseServices.dll", "System.Management.dll", "System.Messaging.dll", "System.Runtime.Remoting.dll", "System.Runtime.Serialization.dll", "System.Runtime.Serialization.Formatters.Soap.dll", "System.Security.dll", "System.ServiceModel.dll", "System.ServiceModel.Web.dll", "System.ServiceProcess.dll", "System.Transactions.dll", "System.Web.dll", "System.Web.Extensions.Design.dll", "System.Web.Extensions.dll", "System.Web.Mobile.dll", "System.Web.RegularExpressions.dll", "System.Web.Services.dll", "System.Windows.Forms.dll", "System.Workflow.Activities.dll", "System.Workflow.ComponentModel.dll", "System.Workflow.Runtime.dll", "System.Xml.dll", "System.Xml.Linq.dll", }, StringComparer.OrdinalIgnoreCase); } [Fact] public void DefaultResponseFileNoConfig() { MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" }); Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[] { MscorlibFullPath, }, StringComparer.OrdinalIgnoreCase); } [Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")] public void TestFilterParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" #pragma warning disable 440 using global = A; // CS0440 class A { static void Main() { #pragma warning suppress 440 } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")] public void TestNoWarnParseDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Test { static void Main() { //Generates warning CS1522: Empty switch block switch (1) { } //Generates warning CS0642: Possible mistaken empty statement while (false) ; { } } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")] public void TestWarnAsError_CS8632() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class C { public string? field; public static void Main() { } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")] public void TestWarnAsError_CS1522() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" public class Test { // CS0169 (level 3) private int x; // CS0109 (level 4) public new void Method() { } public static int Main() { int i = 5; // CS1522 (level 1) switch (i) { } return 0; // CS0162 (level 2) i = 6; } } ").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal( $@"{fileName}(12,20): error CS1522: Empty switch block {fileName}(15,9): error CS0162: Unreachable code detected {fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")] public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path; string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/win32res:" + badres, source }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); CleanupAllGeneratedFiles(badres); } [Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")] public void TestFilterCommandLineDiagnostics() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class A { static void Main() { } }").Path; var baseDir = Path.GetDirectoryName(source); var fileName = Path.GetFileName(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll")); CleanupAllGeneratedFiles(source); } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_Bug15905() { string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@" class Program { #pragma warning disable 1998 public static void Main() { } #pragma warning restore 1998 } ").Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); // Repro case 1 int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); // Repro case 2 exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ExistingPdb() { var dir = Temp.CreateDirectory(); var source1 = dir.CreateFile("program1.cs").WriteAllText(@" class " + new string('a', 10000) + @" { public static void Main() { } }"); var source2 = dir.CreateFile("program2.cs").WriteAllText(@" class Program2 { public static void Main() { } }"); var source3 = dir.CreateFile("program3.cs").WriteAllText(@" class Program3 { public static void Main() { } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int oldSize = 16 * 1024; var exe = dir.CreateFile("Program.exe"); using (var stream = File.OpenWrite(exe.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } var pdb = dir.CreateFile("Program.pdb"); using (var stream = File.OpenWrite(pdb.Path)) { byte[] buffer = new byte[oldSize]; stream.Write(buffer, 0, buffer.Length); } int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter); Assert.NotEqual(0, exitCode1); ValidateZeroes(exe.Path, oldSize); ValidateZeroes(pdb.Path, oldSize); int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter); Assert.Equal(0, exitCode2); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } Assert.True(new FileInfo(exe.Path).Length < oldSize); Assert.True(new FileInfo(pdb.Path).Length < oldSize); int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter); Assert.Equal(0, exitCode3); using (var peFile = File.OpenRead(exe.Path)) { PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false); } } private static void ValidateZeroes(string path, int count) { using (var stream = File.OpenRead(path)) { byte[] buffer = new byte[count]; stream.Read(buffer, 0, buffer.Length); for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != 0) { Assert.True(false); } } } } /// <summary> /// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/> /// the compiler should delete the file to unblock build while allowing the reader to continue /// reading the previous snapshot of the file content. /// /// On Windows we can read the original data directly from the stream without creating a memory map. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void FileShareDeleteCompatibility_Windows() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB"); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter); if (exitCode != 0) { AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString()); } Assert.Equal(0, exitCode); AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2)); AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3)); fsDll.Dispose(); fsPdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } /// <summary> /// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything. /// We need to create the actual memory map. This works on Windows as well. /// </summary> [WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void FileShareDeleteCompatibility_Xplat() { var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01; var mvid = ReadMvid(new MemoryStream(bytes)); var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes); var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var peDll = new PEReader(fsDll); var pePdb = new PEReader(fsPdb); // creates memory map view: var imageDll = peDll.GetEntireImage(); var imagePdb = pePdb.GetEntireImage(); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved.", output); // reading original content from the memory map: Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray()))); Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray()))); // reading original content directly from the streams: fsDll.Position = 0; fsPdb.Position = 0; Assert.Equal(mvid, ReadMvid(fsDll)); Assert.Equal(mvid, ReadMvid(fsPdb)); // reading new content from the file: using (var fsNewDll = File.OpenRead(libDll.Path)) { Assert.NotEqual(mvid, ReadMvid(fsNewDll)); } // Portable PDB metadata signature: AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4)); // dispose PEReaders (they dispose the underlying file streams) peDll.Dispose(); pePdb.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); // files can be deleted now: File.Delete(libSrc.Path); File.Delete(libDll.Path); File.Delete(libPdb.Path); // directory can be deleted (should be empty): Directory.Delete(dir.Path, recursive: false); } private static Guid ReadMvid(Stream stream) { using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen)) { var mdReader = peReader.GetMetadataReader(); return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid); } } // Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes). [ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")] public void FileShareDeleteCompatibility_ReadOnlyFiles() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL"); File.SetAttributes(libDll.Path, FileAttributes.ReadOnly); var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3)); AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3)); fsDll.Dispose(); AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order()); } [Fact] public void FileShareDeleteCompatibility_ExistingDirectory() { var dir = Temp.CreateDirectory(); var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }"); var libDll = dir.CreateDirectory("Lib.dll"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter); Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString()); } private byte[] ReadBytes(Stream stream, int count) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return buffer; } private byte[] ReadBytes(string path, int count) { using (var stream = File.OpenRead(path)) { return ReadBytes(stream, count); } } [Fact] public void IOFailure_DisposeOutputFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposePdbFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe"); var pdbPath = Path.ChangeExtension(exePath, "pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_DisposeXmlFile() { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { return new TestStream(backingStream: new MemoryStream(), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Theory] [InlineData("portable")] [InlineData("full")] public void IOFailure_DisposeSourceLinkFile(string format) { var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path); var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == sourceLinkPath) { return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@" { ""documents"": { ""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*"" } } ")), dispose: () => { throw new IOException("Fake IOException"); }); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString()); } [Fact] public void IOFailure_OpenOutputFile() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == exePath) { throw new IOException(); } return File.Open(file, mode, access, share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(1, csc.Run(outWriter)); Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString()); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenPdbFileNotCalled() { string sourcePath = MakeTrivialExe(); string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe"); string pdbPath = Path.ChangeExtension(exePath, ".pdb"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == pdbPath) { throw new IOException(); } return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); Assert.Equal(0, csc.Run(outWriter)); System.IO.File.Delete(sourcePath); System.IO.File.Delete(exePath); System.IO.File.Delete(pdbPath); CleanupAllGeneratedFiles(sourcePath); } [Fact] public void IOFailure_OpenXmlFinal() { string sourcePath = MakeTrivialExe(); string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath }); csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) => { if (file == xmlPath) { throw new IOException(); } else { return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share); } }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = csc.Run(outWriter); var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath); Assert.Equal(expectedOutput, outWriter.ToString().Trim()); Assert.NotEqual(0, exitCode); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); } private string MakeTrivialExe(string directory = null) { return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@" class Program { public static void Main() { } } ").Path; } [Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")] public void CS1691WRN_BadWarningNumber_AllErrorCodes() { const int jump = 200; for (int i = 0; i < 8000; i += (8000 / jump)) { int startErrorCode = (int)i * jump; int endErrorCode = startErrorCode + jump; string source = ComputeSourceText(startErrorCode, endErrorCode); // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in a #pragma directive // (or via /nowarn /warnaserror flags on the command line). // Going forward, we won't generate any warning in such cases. This will make // maintenance of backwards compatibility easier (we no longer need to worry // about breaking existing projects / command lines if we deprecate / remove // an old warning code). Test(source, startErrorCode, endErrorCode); } } private static string ComputeSourceText(int startErrorCode, int endErrorCode) { string pragmaDisableWarnings = String.Empty; for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @" "; pragmaDisableWarnings += pragmaDisableStr; } return pragmaDisableWarnings + @" public class C { public static void Main() { } }"; } private void Test(string source, int startErrorCode, int endErrorCode) { string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path; var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter); Assert.Equal(0, exitCode); var cscOutput = outWriter.ToString().Trim(); for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++) { Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode); } CleanupAllGeneratedFiles(sourcePath); } [Fact] public void WriteXml() { var source = @" /// <summary> /// A subtype of <see cref=""object""/>. /// </summary> public class C { } "; var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path; string xmlPath = Path.Combine(WorkingDirectory, "Test.xml"); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath }); var writer = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(writer); if (exitCode != 0) { Console.WriteLine(writer.ToString()); Assert.Equal(0, exitCode); } var bytes = File.ReadAllBytes(xmlPath); var actual = new string(Encoding.UTF8.GetChars(bytes)); var expected = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:C""> <summary> A subtype of <see cref=""T:System.Object""/>. </summary> </member> </members> </doc> "; Assert.Equal(expected.Trim(), actual.Trim()); System.IO.File.Delete(xmlPath); System.IO.File.Delete(sourcePath); CleanupAllGeneratedFiles(sourcePath); CleanupAllGeneratedFiles(xmlPath); } [WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void CS2002WRN_FileAlreadyIncluded() { const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times"; TempDirectory tempParentDir = Temp.CreateDirectory(); TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir"); TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }"); // Simple case var commandLineArgs = new[] { "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times string aWrnString = String.Format(cs2002, "a.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString); // Multiple duplicates commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" }; // warning CS2002: Source file 'a.cs' specified multiple times var warnings = new[] { aWrnString }; TestCS2002(commandLineArgs, tempDir.Path, 0, warnings); // Case-insensitive commandLineArgs = new[] { "a.cs", "A.cs" }; // warning CS2002: Source file 'A.cs' specified multiple times string AWrnString = String.Format(cs2002, "A.cs"); TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString); // Different extensions tempDir.CreateFile("a.csx"); commandLineArgs = new[] { "a.cs", "a.csx" }; // No errors or warnings TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty); // Absolute vs Relative commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs"); TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Both relative commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // With wild cards commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // "/recurse" scenarios commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" }; // warning CS2002: Source file 'tmpDir\a.cs' specified multiple times TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString); // Invalid file/path characters const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}"; commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" }; // error CS1504: Source file '{0}' could not be opened: Illegal characters in path. var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str); commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" }; var parseDiags = new[] { // error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"), // error CS2001: Source file 'tmpDi\r*a?.cs' could not be found. Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); char currentDrive = Directory.GetCurrentDirectory()[0]; commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" }; parseDiags = new[] { // error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")}; TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags); commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" }; // error CS1504: Source file '{0}' could not be opened: {1} var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported."); TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504); CleanupAllGeneratedFiles(tempFile.Path); System.IO.Directory.Delete(tempParentDir.Path, true); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics) { TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics); } private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics) { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray(); // Verify command line parser diagnostics. DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics); // Verify compile. int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter); Assert.Equal(expectedExitCode, exitCode); if (parseDiagnostics.IsEmpty()) { // Verify compile diagnostics. string outString = String.Empty; for (int i = 0; i < compileDiagnostics.Length; i++) { if (i != 0) { outString += @" "; } outString += compileDiagnostics[i]; } Assert.Equal(outString, outWriter.ToString().Trim()); } else { Assert.Null(compileDiagnostics); } } [Fact] public void ErrorLineEnd() { var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" }); var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6)); var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc); var text = comp.DiagnosticFormatter.Format(diag); string stringStart = "goo(1,7,1,8)"; Assert.Equal(stringStart, text.Substring(0, stringStart.Length)); } [Fact] public void ReportAnalyzer() { var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory); Assert.True(parsedArgs1.ReportAnalyzer); var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory); Assert.False(parsedArgs2.ReportAnalyzer); } [Fact] public void ReportAnalyzerOutput() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersParse() { var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.True(parsedArgs.SkipAnalyzers); parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.False(parsedArgs.SkipAnalyzers); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void SkipAnalyzersSemantics(bool skipAnalyzers) { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-"); var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path }); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (skipAnalyzers) { Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } else { Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal); Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal); } CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")] public void TestCompilationSuccessIfOnlySuppressedDiagnostics() { var srcFile = Temp.CreateFile().WriteAllText(@" #pragma warning disable Warning01 class C { } "); var errorLog = Temp.CreateFile(); var csc = CreateCSharpCompiler( null, workingDirectory: Path.GetDirectoryName(srcFile.Path), args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer())); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); // Previously, the compiler would return error code 1 without printing any diagnostics Assert.Empty(outWriter.ToString()); Assert.Equal(0, exitCode); CleanupAllGeneratedFiles(srcFile.Path); CleanupAllGeneratedFiles(errorLog.Path); } [Fact] [WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")] public void AnalyzerDiagnosticThrowsInGetMessage() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")] public void AnalyzerExceptionDiagnosticCanBeConfigured() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage())); var exitCode = csc.Run(outWriter); Assert.NotEqual(0, exitCode); var output = outWriter.ToString(); // Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported. Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal); Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] [WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")] public void AnalyzerReportsMisformattedDiagnostic() { var srcFile = Temp.CreateFile().WriteAllText(@"class C {}"); var srcDirectory = Path.GetDirectoryName(srcFile.Path); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic())); var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); // Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message. Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal); Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void ErrorPathsFromLineDirectives() { string sampleProgram = @" #line 10 "".."" //relative path using System* "; var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { }); var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); //Pull off the last segment of the current directory. var expectedPath = Path.GetDirectoryName(WorkingDirectory); //the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info. Assert.Equal('(', text[expectedPath.Length]); sampleProgram = @" #line 10 "".>"" //invalid path character using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith(".>", StringComparison.Ordinal)); sampleProgram = @" #line 10 ""http://goo.bar/baz.aspx"" //URI using System* "; syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs"); text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First()); Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal)); } [WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")] [Fact] public void PreferredUILang() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter); Assert.Equal(1, exitCode); Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")] [Fact] public void EmptyFileName() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter); Assert.NotEqual(0, exitCode); // error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")] [Fact] public void NoInfoDiagnostics() { string filePath = Temp.CreateFile().WriteAllText(@" using System.Diagnostics; // Unused. ").Path; var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); Assert.Equal("", outWriter.ToString().Trim()); CleanupAllGeneratedFiles(filePath); } [Fact] public void RuntimeMetadataVersion() { var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion); parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion); var comp = CreateEmptyCompilation(string.Empty); Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion); comp = CreateEmptyCompilation(string.Empty); Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion); } [WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")] [ConditionalFact(typeof(WindowsOnly))] public void WRN_InvalidSearchPathDir() { var baseDir = Temp.CreateDirectory(); var sourceFile = baseDir.CreateFile("Source.cs"); var invalidPath = "::"; var nonExistentPath = "DoesNotExist"; // lib switch DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid")); DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist")); // LIB environment variable DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify( // warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid")); DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify( // warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist' Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist")); CleanupAllGeneratedFiles(sourceFile.Path); } [WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/55730")] public void ReservedDeviceNameAsFileName() { var parsedArgs = DefaultParse(new[] { "com9.cs", "/t:library " }, WorkingDirectory); Assert.Equal(0, parsedArgs.Errors.Length); parsedArgs = DefaultParse(new[] { "a.cs", "/t:library ", "/appconfig:.\\aux.config" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/out:com1.dll " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/doc:..\\lpt2.xml: " }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "/debug+", "/pdb:.\\prn.pdb" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code); parsedArgs = DefaultParse(new[] { "a.cs", "@con.rsp" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Length); Assert.Equal((int)ErrorCode.ERR_OpenResponseFile, parsedArgs.Errors.First().Code); } [Fact] public void ReservedDeviceNameAsFileName2() { string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path; // make sure reserved device names don't var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal); cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath }); outWriter = new StringWriter(CultureInfo.InvariantCulture); exitCode = cmd.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); } [Fact] public void ParseFeatures() { var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal("Test", args.ParseOptions.Features.Single().Key); args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.ParseOptions.Features.Count); Assert.True(args.ParseOptions.Features.ContainsKey("Test")); Assert.True(args.ParseOptions.Features.ContainsKey("Experiment")); args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } })); args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory); args.Errors.Verify(); Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } })); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void ParseAdditionalFile() { var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path); var baseDir = Temp.CreateDirectory(); baseDir.CreateFile("web1.config"); baseDir.CreateFile("web2.config"); baseDir.CreateFile("web3.config"); args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path); args.Errors.Verify(); Assert.Equal(3, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path); Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path); args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path); Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path); args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(1, args.AdditionalFiles.Length); Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path); args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory); args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile")); Assert.Equal(0, args.AdditionalFiles.Length); } [Fact] public void ParseEditorConfig() { var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single()); args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify(); Assert.Equal(2, args.AnalyzerConfigPaths.Length); Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]); Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]); args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory); args.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1)); Assert.Equal(0, args.AnalyzerConfigPaths.Length); } [Fact] public void NullablePublicOnly() { string source = @"namespace System.Runtime.CompilerServices { public sealed class NullableAttribute : Attribute { } // missing constructor } public class Program { private object? F = null; }"; string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'"; string filePath = Temp.CreateFile().WriteAllText(source).Path; int exitCode; string output; // No /feature (exitCode, output) = compileAndRun(featureOpt: null); Assert.Equal(1, exitCode); Assert.Contains(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly (exitCode, output) = compileAndRun("/features:nullablePublicOnly"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=true (exitCode, output) = compileAndRun("/features:nullablePublicOnly=true"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); // /features:nullablePublicOnly=false (the value is ignored) (exitCode, output) = compileAndRun("/features:nullablePublicOnly=false"); Assert.Equal(0, exitCode); Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(filePath); (int, string) compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return (exitCode, outWriter.ToString()); }; } // See also NullableContextTests.NullableAnalysisFlags_01(). [Fact] public void NullableAnalysisFlags() { string source = @"class Program { #nullable enable static object F1() => null; #nullable disable static object F2() => null; }"; string filePath = Temp.CreateFile().WriteAllText(source).Path; string fileName = Path.GetFileName(filePath); string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." }; string[] expectedWarningsNone = Array.Empty<string>(); AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null)); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always")); AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never")); AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored CleanupAllGeneratedFiles(filePath); string[] compileAndRun(string featureOpt) { var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath }; if (featureOpt != null) args = args.Concat(featureOpt).ToArray(); var compiler = CreateCSharpCompiler(null, WorkingDirectory, args); var outWriter = new StringWriter(CultureInfo.InvariantCulture); int exitCode = compiler.Run(outWriter); return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); }; } [Fact] public void Compiler_Uses_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // with no cache, we'll see the callback execute multiple times RunWithNoCache(); Assert.Equal(1, sourceCallbackCount); RunWithNoCache(); Assert.Equal(2, sourceCallbackCount); RunWithNoCache(); Assert.Equal(3, sourceCallbackCount); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Doesnt_Use_Cache_From_Other_Compilation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // now re-run with a cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(1, sourceCallbackCount); // now emulate a new compilation, and check we were invoked, but only once RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); RunWithCache("2.dll"); Assert.Equal(2, sourceCallbackCount); // now re-run our first compilation RunWithCache("1.dll"); Assert.Equal(2, sourceCallbackCount); // a new one RunWithCache("3.dll"); Assert.Equal(3, sourceCallbackCount); // and another old one RunWithCache("2.dll"); Assert.Equal(3, sourceCallbackCount); RunWithCache("1.dll"); Assert.Equal(3, sourceCallbackCount); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Compiler_Can_Disable_DriverCache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); RunWithCache(); Assert.Equal(1, sourceCallbackCount); // now re-run with the cache disabled sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); // now clear the cache as well as disabling, and verify we don't put any entries into it either cache = new GeneratorDriverCache(); sourceCallbackCount = 0; RunWithCacheDisabled(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); RunWithCacheDisabled(); Assert.Equal(3, sourceCallbackCount); Assert.Equal(0, cache.CacheSize); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:disable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); } [Fact] public void Adding_Or_Removing_A_Generator_Invalidates_Cache() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); int sourceCallbackCount = 0; int sourceCallbackCount2 = 0; var generator = new PipelineCallbackGenerator((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount++; }); }); var generator2 = new PipelineCallbackGenerator2((ctx) => { ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) => { sourceCallbackCount2++; }); }); // run with the cache GeneratorDriverCache cache = new GeneratorDriverCache(); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithOneGenerator(); Assert.Equal(1, sourceCallbackCount); Assert.Equal(0, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); RunWithTwoGenerators(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); // this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when // we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to // RunWithOneGenerator above) meaning we can use the previously cached results and not run. RunWithOneGenerator(); Assert.Equal(2, sourceCallbackCount); Assert.Equal(1, sourceCallbackCount2); void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null); void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null); } private static int OccurrenceCount(string source, string word) { var n = 0; var index = source.IndexOf(word, StringComparison.Ordinal); while (index >= 0) { ++n; index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal); } return n; } private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, int? expectedExitCode = null, bool errorlog = false, bool skipAnalyzers = false, IEnumerable<ISourceGenerator> generators = null, GeneratorDriverCache driverCache = null, params DiagnosticAnalyzer[] analyzers) { var args = new[] { "/nologo", "/preferreduilang:en", "/t:library", sourceFile.Path }; if (includeCurrentAssemblyAsAnalyzerReference) { args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location); } if (errorlog) { args = args.Append("/errorlog:errorlog"); } if (skipAnalyzers) { args = args.Append("/skipAnalyzers"); } if (additionalFlags != null) { args = args.Append(additionalFlags); } var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = csc.Run(outWriter); var output = outWriter.ToString(); expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0; Assert.True( expectedExitCode == exitCode, string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}", expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output)); Assert.DoesNotContain("hidden", output, StringComparison.Ordinal); if (expectedInfoCount == 0) { Assert.DoesNotContain("info", output, StringComparison.Ordinal); } else { // Info diagnostics are only logged with /errorlog. Assert.True(errorlog); Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info")); } if (expectedWarningCount == 0) { Assert.DoesNotContain("warning", output, StringComparison.Ordinal); } else { Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning")); } if (expectedErrorCount == 0) { Assert.DoesNotContain("error", output, StringComparison.Ordinal); } else { Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error")); } return output; } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [Fact] public void NoWarnAndWarnAsError_AnalyzerDriverWarnings() { // This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause // compiler warning CS8032 to be produced when compilations created in this test try to load it. string source = @"using System;"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_HiddenDiagnostic() { // This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden // diagnostics for #region directives present in the compilations created in this test. var source = @"using System; #region Region #endregion"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog) { // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. // This assembly has an InfoDiagnosticAnalyzer type which should produce custom info // diagnostics for the #pragma warning restore directives present in the compilations created in this test. var source = @"using System; #pragma warning restore"; var name = "a.cs"; string output; output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 suppresses custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog); // TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify /nowarn overrides /warnaserror-. output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog); // TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" }); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog); Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); if (errorlog) Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal); } private string GetOutput( string name, string source, bool includeCurrentAssemblyAsAnalyzerReference = true, string[] additionalFlags = null, int expectedInfoCount = 0, int expectedWarningCount = 0, int expectedErrorCount = 0, bool errorlog = false) { var dir = Temp.CreateDirectory(); var file = dir.CreateFile(name); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog); CleanupAllGeneratedFiles(file.Path); return output; } [WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")] [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")] [WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")] [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void NoWarnAndWarnAsError_WarningDiagnostic() { // This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning // diagnostics for source types present in the compilations created in this test. string source = @" class C { static void Main() { int i; } } "; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedWarningCount: 3); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }); Assert.True(string.IsNullOrEmpty(output)); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); // TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:. // This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069). output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /warn:0 overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" }); // TEST: Verify that /warn:0 overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" }); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" }); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" }); // TEST: Verify that /warn:0 overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" }); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-] flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last /warnaserror[+/-]: flag on command line wins. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1); Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-]. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3); Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal); Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")] [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_ErrorDiagnostic() { // This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error // diagnostics for #pragma warning disable directives present in the compilations created in this test. string source = @"using System; #pragma warning disable"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror+:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that /nowarn: overrides /warnaserror-. output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("error CS8032", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign() { var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim()); } [WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")] [Fact] public void NoWarnAndWarnAsError_CompilerErrorDiagnostic() { string source = @"using System; class C { static void Main() { int i = new Exception(); } }"; var dir = Temp.CreateDirectory(); var file = dir.CreateFile("a.cs"); file.WriteAllText(source); var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); // TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:. output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1); Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(file.Path); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins1() { var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(true)); } [WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")] [Fact] public void WarnAsError_LastOneWins2() { var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null); var options = arguments.CompilationOptions; var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)] public class C { public void M(ushort i) { } public static void Main(string[] args) {} }", options: options); comp.VerifyDiagnostics( // (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void M(ushort i) Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i") .WithArguments("ushort") .WithLocation(4, 26) .WithWarningAsError(false)); } [WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")] [WorkItem(444, "CodePlex")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Bug1091972() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText( @" /// <summary>ABC...XYZ</summary> class C { static void Main() { var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml"")); System.Console.WriteLine(textStreamReader.ReadToEnd()); } } "); var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString()); Assert.Equal("", output.Trim()); Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml"))); var expected = @"<?xml version=""1.0""?> <doc> <assembly> <name>out</name> </assembly> <members> <member name=""T:C""> <summary>ABC...XYZ</summary> </member> </members> </doc>".Trim(); using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml"))) { var content = reader.ReadToEnd(); Assert.Equal(expected, content.Trim()); } output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString()); Assert.Equal(expected, output.Trim()); CleanupAllGeneratedFiles(src.Path); } [ConditionalFact(typeof(WindowsOnly))] public void CommandLineMisc() { CSharpCommandLineArguments args = null; string baseDirectory = @"c:\test"; Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory); args = parse(@"/out:""a.exe"""); Assert.Equal(@"a.exe", args.OutputFileName); args = parse(@"/pdb:""a.pdb"""); Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath); // The \ here causes " to be treated as a quote, not as an escaping construct args = parse(@"a\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a""b", @"c:\test\c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"a\\""b c""\d.cs"); Assert.Equal( new[] { @"c:\test\a\b c\d.cs" }, args.SourceFiles.Select(x => x.Path)); args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs"); Assert.Equal( new[] { @"a.dll", @"b.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs"); Assert.Equal( new[] { @"a-s.dll", @"b-s.dll" }, args.MetadataReferences.Select(x => x.Reference)); args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs"); Assert.Equal( new[] { @"a,;s.dll", @"b,;s.dll" }, args.MetadataReferences.Select(x => x.Reference)); } [Fact] public void CommandLine_ScriptRunner1() { var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path)); AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments); args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory); Assert.True(args.InteractiveMode); AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path)); Assert.True(args.SourceFiles[0].IsScript); AssertEx.Equal(new[] { "--" }, args.ScriptArguments); // TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904) // Result: C:\/script.csx //args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\"); //Assert.True(args.InteractiveMode); //AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path)); //Assert.True(args.SourceFiles[0].IsScript); //AssertEx.Equal(new[] { "--" }, args.ScriptArguments); } [WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")] [Fact] public void ParseSeparatedPaths_QuotedComma() { var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b"""); Assert.Equal( new[] { @"a, b" }, paths); } [Fact] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapParser() { var s = PathUtilities.DirectorySeparatorStr; var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap); parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory); Assert.Equal(2, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory); Assert.Equal(1, parsedArgs.Errors.Count()); Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code); parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]); parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]); Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]); } [Theory] [InlineData("", new string[0])] [InlineData(",", new[] { "", "" })] [InlineData(",,", new[] { "," })] [InlineData(",,,", new[] { ",", "" })] [InlineData(",,,,", new[] { ",," })] [InlineData("a,", new[] { "a", "" })] [InlineData("a,b", new[] { "a", "b" })] [InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })] public void SplitWithDoubledSeparatorEscaping(string str, string[] expected) { AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ',')); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbParser() { var dir = Path.Combine(WorkingDirectory, "a"); var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath); // This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it. Assert.Null(parsedArgs.EmitOptions.PdbFilePath); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [CompilerTrait(CompilerFeature.Determinism)] public void PathMapPdbEmit() { void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs) { var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" }; var isDeterministic = extraArgs.Contains("/deterministic"); var args = defaultArgs.Concat(extraArgs).ToArray(); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); Assert.True(File.Exists(pdbPath)); using (var peStream = File.OpenRead(exePath)) { PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic); } } // Case with no mappings using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, pdbPath); } // Simple mapping using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Simple mapping deterministic using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic"); } // Partial mapping using (var dir = new DisposableDirectory(Temp)) { dir.CreateDirectory("pdb"); var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb"); AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\"); } // Legacy feature flag using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism"); } // Unix path map using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/"); } // Multi-specified path map with mixed slashes using (var dir = new DisposableDirectory(Temp)) { var pdbPath = Path.Combine(dir.Path, "a.pdb"); AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar"); } } [CompilerTrait(CompilerFeature.Determinism)] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void DeterministicPdbsRegardlessOfBitness() { var dir = Temp.CreateDirectory(); var dir32 = dir.CreateDirectory("32"); var dir64 = dir.CreateDirectory("64"); var programExe32 = dir32.CreateFile("Program.exe"); var programPdb32 = dir32.CreateFile("Program.pdb"); var programExe64 = dir64.CreateFile("Program.exe"); var programPdb64 = dir64.CreateFile("Program.pdb"); var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@" using System; using System.Linq; using System.Collections.Generic; namespace N { using I4 = System.Int32; class Program { public static IEnumerable<int> F() { I4 x = 1; yield return 1; yield return x; } public static void Main(string[] args) { dynamic x = 1; const int a = 1; F().ToArray(); Console.WriteLine(x + a); } } }"); var csc32src = $@" using System; using System.Reflection; class Runner {{ static int Main(string[] args) {{ var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}""); var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program""); var main = program.GetMethod(""Main""); return (int)main.Invoke(null, new object[] {{ args }}); }} }} "; var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32"); var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray()); dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config"); dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp")); var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path); Assert.Equal("", output); output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path); Assert.Equal("", output); AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes()); AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes()); } [WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void Version() { var folderName = Temp.CreateDirectory().ToString(); var argss = new[] { "/version", "a.cs /version /preferreduilang:en", "/version /nologo", "/version /help", }; foreach (var args in argss) { var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName); Assert.Equal(s_compilerVersion, output.Trim()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void RefOut() { var dir = Temp.CreateDirectory(); var refDir = dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" public class C { /// <summary>Main method</summary> public static void Main() { System.Console.Write(""Hello""); } /// <summary>Private method</summary> private static void PrivateMethod() { System.Console.Write(""Private""); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exe = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exe)); MetadataReaderUtils.VerifyPEMetadata(exe, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" } ); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""M:C.PrivateMethod""> <summary>Private method</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path); Assert.Equal("Hello", output.Trim()); var refDll = Path.Combine(refDir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); CleanupAllGeneratedFiles(refDir.Path); } [Fact] public void RefOutWithError() { var dir = Temp.CreateDirectory(); dir.CreateDirectory("ref"); var src = dir.CreateFile("a.cs"); src.WriteAllText(@"class C { public static void Main() { error(); } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal(1, exitCode); var dll = Path.Combine(dir.Path, "a.dll"); Assert.False(File.Exists(dll)); var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll")); Assert.False(File.Exists(refDll)); Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void RefOnly() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("a.cs"); src.WriteAllText(@" using System; class C { /// <summary>Main method</summary> public static void Main() { error(); // semantic error in method body } private event Action E1 { add { } remove { } } private event Action E2; /// <summary>Private Class Field</summary> private int field; /// <summary>Private Struct</summary> private struct S { /// <summary>Private Struct Field</summary> private int field; } }"); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" }); int exitCode = csc.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var refDll = Path.Combine(dir.Path, "a.dll"); Assert.True(File.Exists(refDll)); // The types and members that are included needs further refinement. // See issue https://github.com/dotnet/roslyn/issues/17612 MetadataReaderUtils.VerifyPEMetadata(refDll, new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" }, new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" }, new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" } ); var pdb = Path.Combine(dir.Path, "a.pdb"); Assert.False(File.Exists(pdb)); var doc = Path.Combine(dir.Path, "doc.xml"); Assert.True(File.Exists(doc)); var content = File.ReadAllText(doc); var expectedDoc = @"<?xml version=""1.0""?> <doc> <assembly> <name>a</name> </assembly> <members> <member name=""M:C.Main""> <summary>Main method</summary> </member> <member name=""F:C.field""> <summary>Private Class Field</summary> </member> <member name=""T:C.S""> <summary>Private Struct</summary> </member> <member name=""F:C.S.field""> <summary>Private Struct Field</summary> </member> </members> </doc>"; Assert.Equal(expectedDoc, content.Trim()); // Clean up temp files CleanupAllGeneratedFiles(dir.Path); } [Fact] public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1)); } [Fact] public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics() { var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values. Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1)); } [Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")] public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut() { var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory); parsedArgs.Errors.Verify( // warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"), // warning CS2029: Invalid value for '/define'; '4' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"), // warning CS2029: Invalid value for '/define'; '5' is not a valid identifier Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5")); } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MissingCompilerAssembly() { var dir = Temp.CreateDirectory(); var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path; dir.CopyFile(typeof(Compilation).Assembly.Location); // Missing Microsoft.CodeAnalysis.CSharp.dll. var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); // Missing System.Collections.Immutable.dll. dir.CopyFile(typeof(CSharpCompilation).Assembly.Location); result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path); Assert.Equal(1, result.ExitCode); Assert.Equal( $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } #if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadinganalyzerNetStandard13() { var analyzerFileName = "AnalyzerNS13.dll"; var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); var outputWithoutPaths = Regex.Replace(result.Output, " in .*", ""); AssertEx.AssertEqualToleratingWhitespaceDifferences( $@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'. System.NotImplementedException: 28 at TestAnalyzer.get_SupportedDiagnostics() at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info) -----", outputWithoutPaths); Assert.Equal(0, result.ExitCode); } #endif private static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) { var minSystemCollectionsImmutableSource = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] namespace System.Collections.Immutable { public struct ImmutableArray<T> { } } "; var minCodeAnalysisSource = @" using System; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace Microsoft.CodeAnalysis.Diagnostics { [AttributeUsage(AttributeTargets.Class)] public sealed class DiagnosticAnalyzerAttribute : Attribute { public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} } public abstract class DiagnosticAnalyzer { public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void Initialize(AnalysisContext context); } public abstract class AnalysisContext { } } namespace Microsoft.CodeAnalysis { public sealed class DiagnosticDescriptor { } } "; var minSystemCollectionsImmutableImage = CSharpCompilation.Create( "System.Collections.Immutable", new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, new MetadataReference[] { NetStandard13.SystemRuntime }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); var minCodeAnalysisImage = CSharpCompilation.Create( "Microsoft.CodeAnalysis", new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, new MetadataReference[] { NetStandard13.SystemRuntime, minSystemCollectionsImmutableRef }, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); var analyzerSource = @" using System; using System.Collections.ObjectModel; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Win32.SafeHandles; [DiagnosticAnalyzer(""C#"")] public class TestAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[] { typeof(Win32Exception), // Microsoft.Win32.Primitives typeof(AppContext), // System.AppContext typeof(Console), // System.Console typeof(ValueTuple), // System.ValueTuple typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo typeof(Process), // System.Diagnostics.Process typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars typeof(ZipArchive), // System.IO.Compression typeof(ZipFile), // System.IO.Compression.ZipFile typeof(FileOptions), // System.IO.FileSystem typeof(FileAttributes), // System.IO.FileSystem.Primitives typeof(HttpClient), // System.Net.Http typeof(AuthenticatedStream), // System.Net.Security typeof(IOControlCode), // System.Net.Sockets typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation typeof(SerializationException), // System.Runtime.Serialization.Primitives typeof(GenericIdentity), // System.Security.Claims typeof(Aes), // System.Security.Cryptography.Algorithms typeof(CspParameters), // System.Security.Cryptography.Csp typeof(AsnEncodedData), // System.Security.Cryptography.Encoding typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates typeof(IXmlLineInfo), // System.Xml.ReaderWriter typeof(XmlNode), // System.Xml.XmlDocument typeof(XPathDocument), // System.Xml.XPath typeof(XDocumentExtensions), // System.Xml.XPath.XDocument typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages typeof(ValueTask<>), // System.Threading.Tasks.Extensions // csc doesn't ship with facades for the following assemblies. // Analyzers can't use them unless they carry the facade with them. // typeof(SafePipeHandle), // System.IO.Pipes // typeof(StackFrame), // System.Diagnostics.StackTrace // typeof(BindingFlags), // System.Reflection.TypeExtensions // typeof(AccessControlActions), // System.Security.AccessControl // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows // typeof(Thread), // System.Threading.Thread }.Length.ToString()); public override void Initialize(AnalysisContext context) { } }"; var references = new MetadataReference[] { minCodeAnalysisRef, minSystemCollectionsImmutableRef }; references = references.Concat(NetStandard13.All).ToArray(); var analyzerImage = CSharpCompilation.Create( analyzerAssemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, references: references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); return analyzerImage; } [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() { var dir = Temp.CreateDirectory(); var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable); // copy csc and dependencies except for DSRN: foreach (var filePath in Directory.EnumerateFiles(cscDir)) { var fileName = Path.GetFileName(filePath); if (fileName.StartsWith("csc") || fileName.StartsWith("System.") || fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native")) { dir.CopyFile(filePath); } } dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }"); var cscCopy = Path.Combine(dir.Path, "csc.exe"); var arguments = "/nologo /t:library /debug:full Source.cs"; // env variable not set (deterministic) -- DSRN is required: var result = ProcessUtilities.Run(cscCopy, arguments + " /deterministic", workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences( "error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " + "The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim()); // env variable not set (non-deterministic) -- globally registered SymReader is picked up: result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim()); // env variable set: result = ProcessUtilities.Run( cscCopy, arguments + " /deterministic", workingDirectory: dir.Path, additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) }); Assert.Equal("", result.Output.Trim()); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")] public void PdbPathNotEmittedWithoutPdb() { var dir = Temp.CreateDirectory(); var source = @"class Program { static void Main() { } }"; var src = dir.CreateFile("a.cs").WriteAllText(source); var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" }; var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler(null, dir.Path, args); int exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var exePath = Path.Combine(dir.Path, "a.exe"); Assert.True(File.Exists(exePath)); using (var peStream = File.OpenRead(exePath)) using (var peReader = new PEReader(peStream)) { var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory; Assert.Equal(0, debugDirectory.Size); Assert.Equal(0, debugDirectory.RelativeVirtualAddress); } } [Fact] public void StrongNameProviderWithCustomTempPath() { var tempDir = Temp.CreateDirectory(); var workingDir = Temp.CreateDirectory(); workingDir.CreateFile("a.cs"); var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path); var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" }); var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null); Assert.True(!comp.SignUsingBuilder); } public class QuotedArgumentTests : CommandLineTestBase { private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows ? @"c:\" : "/"; private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); } private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue) { var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath); Assert.Equal(0, args.Errors.Length); Assert.Equal(expected, getValue(args)); args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath); Assert.True(args.Errors.Length > 0); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void DebugFlag() { var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; var list = new List<Tuple<string, DebugInformationFormat>>() { Tuple.Create("portable", DebugInformationFormat.PortablePdb), Tuple.Create("full", platformPdbKind), Tuple.Create("pdbonly", platformPdbKind), Tuple.Create("embedded", DebugInformationFormat.Embedded) }; foreach (var tuple in list) { VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")] public void CodePage() { VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void Target() { var list = new List<Tuple<string, OutputKind>>() { Tuple.Create("exe", OutputKind.ConsoleApplication), Tuple.Create("winexe", OutputKind.WindowsApplication), Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary), Tuple.Create("module", OutputKind.NetModule), Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication), Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata) }; foreach (var tuple in list) { VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void PlatformFlag() { var list = new List<Tuple<string, Platform>>() { Tuple.Create("x86", Platform.X86), Tuple.Create("x64", Platform.X64), Tuple.Create("itanium", Platform.Itanium), Tuple.Create("anycpu", Platform.AnyCpu), Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred), Tuple.Create("arm", Platform.Arm) }; foreach (var tuple in list) { VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform); } } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void WarnFlag() { VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel); } [WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")] [Fact] public void LangVersionFlag() { VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion); } } [Fact] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidPathCharacterInPathMap() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pathmap:test\\=\"", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")] public void InvalidPathCharacterInPdbPath() { string filePath = Temp.CreateFile().WriteAllText("").Path; var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[] { filePath, "/debug:embedded", "/pdb:test\\?.pdb", "/target:library", "/preferreduilang:en" }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = compiler.Run(outWriter); Assert.Equal(1, exitCode); Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_CompilerParserWarningAsError() { string source = @" class C { long M(int i) { // warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity return 0l; } } "; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that parser warning CS0078 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("warning CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0078", output, StringComparison.Ordinal); // Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0078"); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: suppressor); Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData] public void TestSuppression_CompilerSyntaxWarning(bool skipAnalyzers) { // warning CS1522: Empty switch block // NOTE: Empty switch block warning is reported by the C# language parser string source = @" class C { void M(int i) { switch (i) { } } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS1522 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("warning CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS1522"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains($"info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("error CS1522", output, StringComparison.Ordinal); // Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, skipAnalyzers: skipAnalyzers, analyzers: suppressor); Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData] public void TestSuppression_CompilerSemanticWarning(bool skipAnalyzers) { string source = @" class C { // warning CS0169: The field 'C.f' is never used private readonly int f; }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler warning CS0169 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("warning CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId("CS0169"); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture), suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers); Assert.Contains("error CS0169", output, StringComparison.Ordinal); // Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, skipAnalyzers: skipAnalyzers, analyzers: suppressor); Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal); Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSyntaxError() { // error CS1001: Identifier expected string source = @" class { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler syntax error CS1001 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS1001", output, StringComparison.Ordinal); // Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS1001")); Assert.Contains("error CS1001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_CompilerSemanticError() { // error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) string source = @" class C { void M(UndefinedType x) { } }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that compiler error CS0246 is reported. var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.Contains("error CS0246", output, StringComparison.Ordinal); // Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new DiagnosticSuppressorForId("CS0246")); Assert.Contains("error CS0246", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [ConditionalFact(typeof(IsEnglishLocal))] public void TestSuppression_AnalyzerWarning() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer warning is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor // and info diagnostic is logged with programmatic suppression information. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); // Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}' var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage, suppressor.SuppressionDescriptor.SuppressedDiagnosticId, analyzer.Descriptor.MessageFormat, suppressor.SuppressionDescriptor.Id, suppressor.SuppressionDescriptor.Justification); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that analyzer warning is reported as error for /warnaserror. output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror // and info diagnostic is logged with programmatic suppression information. output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, errorlog: true, analyzers: analyzerAndSuppressor); Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); Assert.Contains("info SP0001", output, StringComparison.Ordinal); Assert.Contains(suppressionMessage, output, StringComparison.Ordinal); // Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor. analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false); suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] [Fact] public void TestNoSuppression_AnalyzerError() { string source = @" class C { }"; var srcDirectory = Temp.CreateDirectory(); var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); // Verify that analyzer error is reported. var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true); var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzer); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); // Verify that analyzer error cannot be suppressed with diagnostic suppressor. var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id); var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor }; output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: analyzerAndSuppressor); Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcFile.Path); } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify category based configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify category based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify category based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify global config based configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" is_global = true dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by category based configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify disabled by default analyzer is not enabled by category based configuration in global config analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" is_global=true dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer via global config analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; // Verify bulk configuration without any diagnostic ID configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify bulk configuration does not get applied for suppressed diagnostic. TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true); // Verify bulk configuration does not get applied for diagnostic configured in ruleset. var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText); // Verify bulk configuration before diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error dotnet_diagnostic.{diagnosticId}.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify bulk configuration after diagnostic ID configuration is not respected. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify disabled by default analyzer is not enabled by bulk configuration. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity); analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); if (defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog) { // Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed. analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); // Verify that bulk configuration 'none' entry does not enable this analyzer. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = none"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress); } } [WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")] [InlineData(DiagnosticSeverity.Warning, false)] [InlineData(DiagnosticSeverity.Info, true)] [InlineData(DiagnosticSeverity.Info, false)] [InlineData(DiagnosticSeverity.Hidden, false)] [Theory] public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity); var diagnosticId = analyzer.Descriptor.Id; var category = analyzer.Descriptor.Category; // Verify category based configuration before bulk analyzer diagnostic configuration is respected. var analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = error dotnet_analyzer_diagnostic.severity = warning"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify category based configuration after bulk analyzer diagnostic configuration is respected. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = error"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config. analyzerConfigText = $@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = warning dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn); // Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset. analyzerConfigText = $@" [*.cs] dotnet_analyzer_diagnostic.category-{category}.severity = none dotnet_analyzer_diagnostic.severity = suggestion"; var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""{diagnosticId}"" Action=""Warning"" /> </Rules> </RuleSet>"; TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText); } private void TestBulkAnalyzerConfigurationCore( NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer, string analyzerConfigText, bool errorlog, ReportDiagnostic expectedDiagnosticSeverity, string rulesetText = null, bool noWarn = false) { var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{diagnosticId}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } if (rulesetText != null) { var rulesetFile = CreateRuleSetFile(rulesetText); arguments = arguments.Append($"/ruleset:{rulesetFile.Path}"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); var prefix = expectedDiagnosticSeverity switch { ReportDiagnostic.Error => "error", ReportDiagnostic.Warn => "warning", ReportDiagnostic.Info => errorlog ? "info" : null, ReportDiagnostic.Hidden => null, ReportDiagnostic.Suppress => null, _ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity) }; if (prefix == null) { Assert.DoesNotContain(diagnosticId, outWriter.ToString()); } else { Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString()); } } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (warnAsError) { additionalArgs = additionalArgs.Append("/warnaserror").AsArray(); } var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !warnAsError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !warnAsError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (analyzerConfigSetToError) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.cs0169.severity = error"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } var expectedErrorCount = analyzerConfigSetToError ? 1 : 0; var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { int _f; // CS0169: unused field }"); var docName = "temp.xml"; var pdbName = "temp.pdb"; var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" }; if (rulesetSetToError) { string source = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis""> <Rule Id=""CS0169"" Action=""Error"" /> </Rules> </RuleSet> "; var rulesetFile = CreateRuleSetFile(source); additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray(); } var expectedErrorCount = rulesetSetToError ? 1 : 0; var expectedWarningCount = !rulesetSetToError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount); var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169"; Assert.Contains(expectedOutput, output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !rulesetSetToError); string pdbPath = Path.Combine(dir.Path, pdbName); Assert.True(File.Exists(pdbPath) == !rulesetSetToError); string xmlDocFilePath = Path.Combine(dir.Path, docName); Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText("class C { }"); var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null; var expectedErrorCount = warnAsError ? 1 : 0; var expectedWarningCount = !warnAsError ? 1 : 0; var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectedErrorCount, expectedWarningCount: expectedWarningCount, analyzers: new[] { new WarningDiagnosticAnalyzer() }); var expectedDiagnosticSeverity = warnAsError ? "error" : "warning"; Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output); string binaryPath = Path.Combine(dir.Path, "temp.dll"); Assert.True(File.Exists(binaryPath) == !warnAsError); } // Currently, configuring no location diagnostics through editorconfig is not supported. [Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")] [CombinatorialData] public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog); } [WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")] [Theory] [CombinatorialData] public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning); TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog); } private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog) { if (analyzerConfigSeverity == ReportDiagnostic.Default) { // "dotnet_diagnostic.ID.severity = default" is not supported. return; } var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}"); var arguments = new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig.Path, src.Path }; if (noWarn) { arguments = arguments.Append($"/nowarn:{descriptor.Id}"); } if (errorlog) { arguments = arguments.Append($"/errorlog:errorlog"); } var cmd = CreateCSharpCompiler(null, dir.Path, arguments, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0; Assert.Equal(expectedErrorCode, exitCode); // NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details. if (!noWarn && (analyzerConfigSeverity == ReportDiagnostic.Error || analyzerConfigSeverity == ReportDiagnostic.Warn || (analyzerConfigSeverity == ReportDiagnostic.Info && errorlog))) { var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info"; Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString()); } else { Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString()); } } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void IsUserConfiguredGeneratedCodeInAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = true var analyzerConfigFile = dir.CreateFile(".editorconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = true"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source. Assert.Contains("warning CS8669", output, StringComparison.Ordinal); // generated_code = false analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = false"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); // generated_code = auto analyzerConfig = analyzerConfigFile.WriteAllText(@" [*.cs] generated_code = auto"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning CS8602: Dereference of a possibly null reference. Assert.Contains("warning CS8602", output, StringComparison.Ordinal); } [WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")] [CombinatorialData, Theory] public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog) { // This test verifies that analyzer execution is skipped at build time for the following: // 1. Analyzer reporting Hidden diagnostics // 2. Analyzer reporting Info diagnostics, when /errorlog is not specified var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info && !errorlog; // We use an analyzer that throws an exception on every analyzer callback. // So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not. var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path }; if (errorlog) args = args.Append("/errorlog:errorlog"); var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'", output, StringComparison.Ordinal); } } [WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")] [CombinatorialData, Theory] public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault) { // This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped.. // Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped: // 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'. // 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds. var analyzerShouldBeSkipped = !isEnabledByDefault || defaultSeverity == DiagnosticSeverity.Hidden || defaultSeverity == DiagnosticSeverity.Info; var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); // Verify '/warnaserror-:DiagnosticId' behavior. var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0; Assert.Equal(expectedExitCode, exitCode); var output = outWriter.ToString(); if (analyzerShouldBeSkipped) { Assert.Empty(output); } else { var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error"; Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output); } } [WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")] [Theory] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified. [InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)] // Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error' [InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] [InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)] public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig( bool warnAsErrorMinus, DiagnosticSeverity defaultSeverity, DiagnosticSeverity? severityInConfigFile, DiagnosticSeverity expectedEffectiveSeverity) { var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false); var diagnosticId = analyzer.Descriptor.Id; var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }"); var additionalFlags = new[] { "/warnaserror+" }; if (severityInConfigFile.HasValue) { var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString(); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {severityString}"); additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray(); } if (warnAsErrorMinus) { additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray(); } int expectedWarningCount = 0, expectedErrorCount = 0; switch (expectedEffectiveSeverity) { case DiagnosticSeverity.Warning: expectedWarningCount = 1; break; case DiagnosticSeverity.Error: expectedErrorCount = 1; break; default: throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity); } VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, expectedWarningCount: expectedWarningCount, expectedErrorCount: expectedErrorCount, additionalFlags: additionalFlags, analyzers: new[] { analyzer }); } [Fact] public void SourceGenerators_EmbeddedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); // 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution. var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-"); // Verify analyzers were executed only if both the following conditions were satisfied: // 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and // 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false". var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers; // 'WarningDiagnosticAnalyzer' generates a warning for each named type. // We expect two warnings for this test: type "C" defined in source and the source generator defined type. // Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created" // CS8032 is generated with includeCurrentAssemblyAsAnalyzerReference even when we are skipping analyzers as we will instantiate all analyzers, just not execute them. var expectedWarningCount = expectedAnalyzerExecution ? 3 : (includeCurrentAssemblyAsAnalyzerReference ? 1 : 0); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference, expectedWarningCount: expectedWarningCount, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag }, generators: new[] { generator }); // Verify source generator was executed, regardless of the value of 'skipAnalyzers'. var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true); if (expectedAnalyzerExecution) { Assert.Contains("warning Warning01", output, StringComparison.Ordinal); Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else if (includeCurrentAssemblyAsAnalyzerReference) { Assert.Contains("warning CS8032", output, StringComparison.Ordinal); } else { Assert.Empty(output); } // Clean up temp files CleanupAllGeneratedFiles(src.Path); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generator1Prefix, source1Name), source1}, { Path.Combine(dir.Path, generator2Prefix, source2Name), source2}, }, dir, true); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_WriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_OverwriteGeneratedSources() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource1 = "class D { } class E { }"; var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } }); var generatedSource2 = "public class D { }"; var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Theory] [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names [InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names [InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names [InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generator = new SingleFileTestGenerator(source1, source1Name); var generator2 = new SingleFileTestGenerator2(source2, source2Name); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null); var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } }, { Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading [WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")] public void SourceGenerators_SxS_AssemblyLoading() { // compile the generators var dir = Temp.CreateDirectory(); var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey); var src = dir.CreateFile("generator.cs"); var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path)); string createGenerator(string version) { var generatorSource = $@" using Microsoft.CodeAnalysis; [assembly:System.Reflection.AssemblyVersion(""{version}"")] [Generator] public class TestGenerator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll"); var comp = CreateEmptyCompilation(source: generatorSource, references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)), options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider), assemblyName: "generator"); comp.VerifyDiagnostics(); comp.Emit(path); return path; } var gen1 = createGenerator("1.0.0.0"); var gen2 = createGenerator("2.0.0.0"); var generatedDir = dir.CreateDirectory("generated"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray()); // This is wrong! Both generators are writing the same file out, over the top of each other // See https://github.com/dotnet/roslyn/issues/47990 ValidateWrittenSources(new() { // { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } }, { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } } }); } [Fact] public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); ValidateWrittenSources(new() { { generatedDir.Path, new() } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_Error_When_GeneratedDir_NotExist() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDirPath = Path.Combine(dir.Path, "noexist"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); Assert.Contains("CS0016:", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_GeneratedDir_Has_Spaces() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated files"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator); ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } }); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void ParseGeneratedFilesOut() { string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\"; string baseDirectory = Path.Combine(root, "abc", "def"); var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify( // error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\"")); Assert.Null(parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory); var absPath = Path.Combine(root, "outdir"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); absPath = Path.Combine(root, "generated files"); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory); parsedArgs.Errors.Verify(); Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory); } [Fact] public void SourceGenerators_Error_When_NoDirectoryArgumentGiven() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" }); Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var generatedDir = dir.CreateDirectory("generated"); var generatedSource = "public class D { }"; var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null); var touchedFiles = Directory.GetFiles(dir.Path, "touched*"); Assert.Equal(2, touchedFiles.Length); string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write")); Assert.Equal(2, writtenText.Length); Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase); Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase); // Clean up temp files CleanupAllGeneratedFiles(src.Path); Directory.Delete(dir.Path, true); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")] public void SourceGeneratorsAndAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key = value"); var generator = new SingleFileTestGenerator("public class D {}", "generated.cs"); VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null); } [Fact] public void SourceGeneratorsCanReadAnalyzerConfig() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@" is_global = true key1 = value1 [*.cs] key2 = value2 [*.vb] key3 = value3"); var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key4 = value4 [*.vb] key5 = value5"); var subDir = dir.CreateDirectory("subDir"); var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key6 = value6 [*.vb] key7 = value7"); var generator = new CallbackGenerator((ic) => { }, (gc) => { // can get the global options var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // can get the options for class C var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); }); var args = new[] { "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, "/analyzerconfig:" + analyzerConfig3.Path, "/t:library", src.Path }; var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator)); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); // test for both the original tree and the generated one var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; // get the global options var globalOptions = provider.GlobalOptions; Assert.True(globalOptions.TryGetValue("key1", out var keyValue)); Assert.Equal("value1", keyValue); Assert.False(globalOptions.TryGetValue("key2", out _)); Assert.False(globalOptions.TryGetValue("key3", out _)); Assert.False(globalOptions.TryGetValue("key4", out _)); Assert.False(globalOptions.TryGetValue("key5", out _)); Assert.False(globalOptions.TryGetValue("key6", out _)); Assert.False(globalOptions.TryGetValue("key7", out _)); // get the options for class C var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First()); Assert.True(classOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(classOptions.TryGetValue("key2", out _)); Assert.False(classOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(classOptions.TryGetValue("key5", out _)); Assert.False(classOptions.TryGetValue("key6", out _)); Assert.False(classOptions.TryGetValue("key7", out _)); // get the options for generated class D var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last()); Assert.True(generatedOptions.TryGetValue("key1", out keyValue)); Assert.Equal("value1", keyValue); Assert.False(generatedOptions.TryGetValue("key2", out _)); Assert.False(generatedOptions.TryGetValue("key3", out _)); Assert.True(classOptions.TryGetValue("key4", out keyValue)); Assert.Equal("value4", keyValue); Assert.False(generatedOptions.TryGetValue("key5", out _)); Assert.False(generatedOptions.TryGetValue("key6", out _)); Assert.False(generatedOptions.TryGetValue("key7", out _)); } [Theory] [CombinatorialData] public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}"); var generator = new CallbackGenerator(i => { }, e => throw null); var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0); Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output); } [DiagnosticAnalyzer(LanguageNames.CSharp)] private sealed class FieldAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { } } [Fact] [WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")] public void TupleField_ForceComplete() { var source = @"namespace System { public struct ValueTuple<T1> { public T1 Item1; public ValueTuple(T1 item1) { Item1 = item1; } } }"; var srcFile = Temp.CreateFile().WriteAllText(source); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var csc = CreateCSharpCompiler( null, WorkingDirectory, new[] { "/nologo", "/t:library", srcFile.Path }, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required var exitCode = csc.Run(outWriter); Assert.Equal(0, exitCode); var output = outWriter.ToString(); Assert.Empty(output); CleanupAllGeneratedFiles(srcFile.Path); } [Fact] public void GlobalAnalyzerConfigsAllowedInSameDir() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { int _f; }"); var configText = @" is_global = true "; var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText); var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", "/analyzerconfig:" + analyzerConfig1.Path, "/analyzerconfig:" + analyzerConfig2.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal(0, exitCode); } [Fact] public void GlobalAnalyzerConfigMultipleSetKeys() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { }"); var analyzerConfigFile = dir.CreateFile(".globalconfig"); var analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 option1 = abc"); var analyzerConfigFile2 = dir.CreateFile(".globalconfig2"); var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 option1 = def"); var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'Global Section'", output, StringComparison.Ordinal); analyzerConfig = analyzerConfigFile.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = abc"); analyzerConfig2 = analyzerConfigFile2.WriteAllText(@" is_global = true global_level = 100 [/file.cs] option1 = def"); output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); // warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ... Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal); Assert.Contains("'option1'", output, StringComparison.Ordinal); Assert.Contains("'/file.cs'", output, StringComparison.Ordinal); } [Fact] public void GlobalAnalyzerConfigWithOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var additionalFile = dir.CreateFile("file.txt"); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] key1 = value1 [*.txt] key2 = value2"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true key3 = value3"); var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/analyzerconfig:" + analyzerConfig.Path, "/analyzerconfig:" + globalConfig.Path, "/analyzer:" + Assembly.GetExecutingAssembly().Location, "/nowarn:8032,Warning01", "/additionalfile:" + additionalFile.Path, src.Path }); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); Assert.Equal("", outWriter.ToString()); Assert.Equal(0, exitCode); var comp = cmd.Compilation; var tree = comp.SyntaxTrees.Single(); var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider; var options = provider.GetOptions(tree); Assert.NotNull(options); Assert.True(options.TryGetValue("key1", out string val)); Assert.Equal("value1", val); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single()); Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.True(options.TryGetValue("key2", out val)); Assert.Equal("value2", val); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); options = provider.GlobalOptions; Assert.NotNull(options); Assert.False(options.TryGetValue("key1", out _)); Assert.False(options.TryGetValue("key2", out _)); Assert.True(options.TryGetValue("key3", out val)); Assert.Equal("value3", val); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.CS0164.severity = error; "); var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@" [*.cs] dotnet_diagnostic.CS0164.severity = warning; "); var none = Array.Empty<TempFile>(); var globalOnly = new[] { globalConfig }; var globalAndSpecific = new[] { globalConfig, analyzerConfig }; // by default a warning, which can be suppressed via cmdline verify(configs: none, expectedWarnings: 1); verify(configs: none, noWarn: "CS0164", expectedWarnings: 0); // the global analyzer config ups the warning to an error, but the cmdline setting overrides it verify(configs: globalOnly, expectedErrors: 1); verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0); verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works // the editor config downgrades the error back to warning, but the cmdline setting overrides it verify(configs: globalAndSpecific, expectedWarnings: 1); verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0); void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0") => VerifyOutput(dir, src, expectedErrorCount: expectedErrors, expectedWarningCount: expectedWarnings, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: null, additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path) .Add("/noWarn:" + noWarn).ToArray()); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = none; "); VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false); } [Theory, CombinatorialData] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig) { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var additionalFlags = new[] { "/warnaserror+" }; if (useGlobalConfig) { var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true dotnet_diagnostic.CS0164.severity = warning; "); additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray(); } else { string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0""> <Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler""> <Rule Id=""CS0164"" Action=""Warning"" /> </Rules> </RuleSet> "; _ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource); additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray(); } VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(@" class C { void M() { label1:; } }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@" is_global = true [{PathUtilities.NormalizeWithForwardSlash(src.Path)}] dotnet_diagnostic.CS0164.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false); } [Fact] [WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")] public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation() { var dir = Temp.CreateDirectory(); var src = dir.CreateFile("test.cs").WriteAllText(@" class C { }"); var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@" is_global = true dotnet_diagnostic.Warning01.severity = error; "); VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer()); } [Theory, CombinatorialData] public void TestAdditionalFileAnalyzer(bool registerFromInitialize) { var srcDirectory = Temp.CreateDirectory(); var source = "class C { }"; var srcFile = srcDirectory.CreateFile("a.cs"); srcFile.WriteAllText(source); var additionalText = "Additional Text"; var additionalFile = srcDirectory.CreateFile("b.txt"); additionalFile.WriteAllText(additionalText); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/additionalfile:" + additionalFile.Path }, analyzers: analyzer); Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal); CleanupAllGeneratedFiles(srcDirectory.Path); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:CS0169" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var src = @" class C { int _f; // CS0169: unused field }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning); } [Theory] // "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)] // "/warnaserror:DiagnosticId" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)] // "/nowarn" tests [InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)] // Neither "/nowarn" nor "/warnaserror" tests [InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)] [InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)] [WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")] public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning) { var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true); var src = @"class C { }"; TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer); } private void TestCompilationOptionsOverrideAnalyzerConfigCore( string source, string diagnosticId, string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning, params DiagnosticAnalyzer[] analyzers) { Assert.True(!expectError || !expectWarning); var dir = Temp.CreateDirectory(); var src = dir.CreateFile("temp.cs").WriteAllText(source); var additionalArgs = Array.Empty<string>(); if (analyzerConfigSeverity != null) { var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@" [*.cs] dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}"); additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray(); } if (!string.IsNullOrEmpty(additionalArg)) { additionalArgs = additionalArgs.Append(additionalArg); } var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalArgs, expectedErrorCount: expectError ? 1 : 0, expectedWarningCount: expectWarning ? 1 : 0, analyzers: analyzers); if (expectError) { Assert.Contains($"error {diagnosticId}", output); } else if (expectWarning) { Assert.Contains($"warning {diagnosticId}", output); } else { Assert.DoesNotContain(diagnosticId, output); } } [ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")] public void TestGeneratorsCantTargetNetFramework() { var directory = Temp.CreateDirectory(); var src = directory.CreateFile("test.cs").WriteAllText(@" class C { }"); // core var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator }); // netstandard var nsGenerator = emitGenerator(".NETStandard,Version=v2.0"); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator }); // no target var ntGenerator = emitGenerator(targetFramework: null); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator }); // framework var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2"); var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8850", output); // ref's net fx Assert.Contains("CS8033", output); // no analyzers in assembly // framework, suppressed output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator }); Assert.Contains("CS8033", output); VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator }); string emitGenerator(string targetFramework) { string targetFrameworkAttributeText = targetFramework is object ? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]" : string.Empty; string generatorSource = $@" using Microsoft.CodeAnalysis; {targetFrameworkAttributeText} [Generator] public class Generator : ISourceGenerator {{ public void Execute(GeneratorExecutionContext context) {{ }} public void Initialize(GeneratorInitializationContext context) {{ }} }}"; var directory = Temp.CreateDirectory(); var generatorPath = Path.Combine(directory.Path, "generator.dll"); var compilation = CSharpCompilation.Create($"generator", new[] { CSharpSyntaxTree.ParseText(generatorSource) }, TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); compilation.VerifyDiagnostics(); var result = compilation.Emit(generatorPath); Assert.True(result.Success); return generatorPath; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer { public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Hidden01, Hidden02); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation())); } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Info01); } } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword)) { context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation())); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Warning01); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSymbolAction( (symbolContext) => { symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First())); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer { internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true); internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Error01, Error02); } } public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) { nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation())); } }, SyntaxKind.PragmaWarningDirectiveTrivia ); } } }
1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/Core/Portable/CommandLine/CommandLineArguments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Text; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The base class for representing command line arguments to a /// <see cref="CommonCompiler"/>. /// </summary> public abstract class CommandLineArguments { internal bool IsScriptRunner { get; set; } /// <summary> /// Drop to an interactive loop. If a script is specified in <see cref="SourceFiles"/> executes the script first. /// </summary> public bool InteractiveMode { get; internal set; } /// <summary> /// Directory used to resolve relative paths stored in the arguments. /// </summary> /// <remarks> /// Except for paths stored in <see cref="MetadataReferences"/>, all /// paths stored in the properties of this class are resolved and /// absolute. This is the directory that relative paths specified on /// command line were resolved against. /// </remarks> public string? BaseDirectory { get; internal set; } /// <summary> /// A list of pairs of paths. This stores the value of the command-line compiler /// option /pathMap:X1=Y1;X2=Y2... which causes a prefix of X1 followed by a path /// separator to be replaced by Y1 followed by a path separator, and so on for each following pair. /// </summary> /// <remarks> /// This option is used to help get build-to-build determinism even when the build /// directory is different from one build to the next. The prefix matching is case sensitive. /// </remarks> public ImmutableArray<KeyValuePair<string, string>> PathMap { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for references. /// </summary> public ImmutableArray<string> ReferencePaths { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for sources specified as #load directives. /// </summary> public ImmutableArray<string> SourcePaths { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for key files. /// </summary> public ImmutableArray<string> KeyFileSearchPaths { get; internal set; } /// <summary> /// If true, use UTF8 for output. /// </summary> public bool Utf8Output { get; internal set; } /// <summary> /// Compilation name or null if not specified. /// </summary> public string? CompilationName { get; internal set; } /// <summary> /// Gets the emit options. /// </summary> public EmitOptions EmitOptions { get; internal set; } = null!; // initialized by Parse /// <summary> /// Name of the output file or null if not specified. /// </summary> public string? OutputFileName { get; internal set; } /// <summary> /// Path of the output ref assembly or null if not specified. /// </summary> public string? OutputRefFilePath { get; internal set; } /// <summary> /// Path of the PDB file or null if same as output binary path with .pdb extension. /// </summary> public string? PdbPath { get; internal set; } /// <summary> /// Path of the file containing information linking the compilation to source server that stores /// a snapshot of the source code included in the compilation. /// </summary> public string? SourceLink { get; internal set; } /// <summary> /// Absolute path of the .ruleset file or null if not specified. /// </summary> public string? RuleSetPath { get; internal set; } /// <summary> /// True to emit PDB information (to a standalone PDB file or embedded into the PE file). /// </summary> public bool EmitPdb { get; internal set; } /// <summary> /// Absolute path of the output directory (could only be null if there is an error reported). /// </summary> public string OutputDirectory { get; internal set; } = null!; // initialized by Parse /// <summary> /// Absolute path of the documentation comment XML file or null if not specified. /// </summary> public string? DocumentationPath { get; internal set; } /// <summary> /// Absolute path of the directory to place generated files in, or <c>null</c> to not emit any generated files. /// </summary> public string? GeneratedFilesOutputDirectory { get; internal set; } /// <summary> /// Options controlling the generation of a SARIF log file containing compilation or /// analysis diagnostics, or null if no log file is desired. /// </summary> public ErrorLogOptions? ErrorLogOptions { get; internal set; } /// <summary> /// Options controlling the generation of a SARIF log file containing compilation or /// analysis diagnostics, or null if no log file is desired. /// </summary> public string? ErrorLogPath => ErrorLogOptions?.Path; /// <summary> /// An absolute path of the app.config file or null if not specified. /// </summary> public string? AppConfigPath { get; internal set; } /// <summary> /// Errors while parsing the command line arguments. /// </summary> public ImmutableArray<Diagnostic> Errors { get; internal set; } /// <summary> /// References to metadata supplied on the command line. /// Includes assemblies specified via /r and netmodules specified via /addmodule. /// </summary> public ImmutableArray<CommandLineReference> MetadataReferences { get; internal set; } /// <summary> /// References to analyzers supplied on the command line. /// </summary> public ImmutableArray<CommandLineAnalyzerReference> AnalyzerReferences { get; internal set; } /// <summary> /// A set of paths to EditorConfig-compatible analyzer config files. /// </summary> public ImmutableArray<string> AnalyzerConfigPaths { get; internal set; } /// <summary> /// A set of additional non-code text files that can be used by analyzers. /// </summary> public ImmutableArray<CommandLineSourceFile> AdditionalFiles { get; internal set; } /// <summary> /// A set of files to embed in the PDB. /// </summary> public ImmutableArray<CommandLineSourceFile> EmbeddedFiles { get; internal set; } /// <value> /// Report additional information related to analyzers, such as analyzer execution time. /// </value> public bool ReportAnalyzer { get; internal set; } /// <value> /// Skip execution of <see cref="DiagnosticAnalyzer"/>s. /// </value> public bool SkipAnalyzers { get; internal set; } /// <summary> /// If true, prepend the command line header logo during /// <see cref="CommonCompiler.Run"/>. /// </summary> public bool DisplayLogo { get; internal set; } /// <summary> /// If true, append the command line help during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayHelp { get; internal set; } /// <summary> /// If true, append the compiler version during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayVersion { get; internal set; } /// <summary> /// If true, prepend the compiler-supported language versions during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayLangVersions { get; internal set; } /// <summary> /// The path to a Win32 resource. /// </summary> public string? Win32ResourceFile { get; internal set; } /// <summary> /// The path to a .ico icon file. /// </summary> public string? Win32Icon { get; internal set; } /// <summary> /// The path to a Win32 manifest file to embed /// into the output portable executable (PE) file. /// </summary> public string? Win32Manifest { get; internal set; } /// <summary> /// If true, do not embed any Win32 manifest, including /// one specified by <see cref="Win32Manifest"/> or any /// default manifest. /// </summary> public bool NoWin32Manifest { get; internal set; } /// <summary> /// Resources specified as arguments to the compilation. /// </summary> public ImmutableArray<ResourceDescription> ManifestResources { get; internal set; } /// <summary> /// Encoding to be used for source files or 'null' for autodetect/default. /// </summary> public Encoding? Encoding { get; internal set; } /// <summary> /// Hash algorithm to use to calculate source file debug checksums and PDB checksum. /// </summary> public SourceHashAlgorithm ChecksumAlgorithm { get; internal set; } /// <summary> /// Arguments following a script file or separator "--". Null if the command line parser is not interactive. /// </summary> public ImmutableArray<string> ScriptArguments { get; internal set; } /// <summary> /// Source file paths. /// </summary> /// <remarks> /// Includes files specified directly on command line as well as files matching patterns specified /// on command line using '*' and '?' wildcards or /recurse option. /// </remarks> public ImmutableArray<CommandLineSourceFile> SourceFiles { get; internal set; } /// <summary> /// Full path of a log of file paths accessed by the compiler, or null if file logging should be suppressed. /// </summary> /// <remarks> /// Two log files will be created: /// One with path <see cref="TouchedFilesPath"/> and extension ".read" logging the files read, /// and second with path <see cref="TouchedFilesPath"/> and extension ".write" logging the files written to during compilation. /// </remarks> public string? TouchedFilesPath { get; internal set; } /// <summary> /// If true, prints the full path of the file containing errors or /// warnings in diagnostics. /// </summary> public bool PrintFullPaths { get; internal set; } /// <summary> /// Options to the <see cref="CommandLineParser"/>. /// </summary> /// <returns></returns> public ParseOptions ParseOptions { get { return ParseOptionsCore; } } /// <summary> /// Options to the <see cref="Compilation"/>. /// </summary> public CompilationOptions CompilationOptions { get { return CompilationOptionsCore; } } protected abstract ParseOptions ParseOptionsCore { get; } protected abstract CompilationOptions CompilationOptionsCore { get; } /// <summary> /// Specify the preferred output language name. /// </summary> public CultureInfo? PreferredUILang { get; internal set; } internal StrongNameProvider GetStrongNameProvider(StrongNameFileSystem fileSystem) => new DesktopStrongNameProvider(KeyFileSearchPaths, fileSystem); internal CommandLineArguments() { } /// <summary> /// Returns a full path of the file that the compiler will generate the assembly to if compilation succeeds. /// </summary> /// <remarks> /// The method takes <paramref name="outputFileName"/> rather than using the value of <see cref="OutputFileName"/> /// since the latter might be unspecified, in which case actual output path can't be determined for C# command line /// without creating a compilation and finding an entry point. VB does not allow <see cref="OutputFileName"/> to /// be unspecified. /// </remarks> public string GetOutputFilePath(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException(nameof(outputFileName)); } return Path.Combine(OutputDirectory, outputFileName); } /// <summary> /// Returns a full path of the PDB file that the compiler will generate the debug symbols to /// if <see cref="EmitPdbFile"/> is true and the compilation succeeds. /// </summary> /// <remarks> /// The method takes <paramref name="outputFileName"/> rather than using the value of <see cref="OutputFileName"/> /// since the latter might be unspecified, in which case actual output path can't be determined for C# command line /// without creating a compilation and finding an entry point. VB does not allow <see cref="OutputFileName"/> to /// be unspecified. /// </remarks> public string GetPdbFilePath(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException(nameof(outputFileName)); } return PdbPath ?? Path.Combine(OutputDirectory, Path.ChangeExtension(outputFileName, ".pdb")); } /// <summary> /// Returns true if the PDB is generated to a PDB file, as opposed to embedded to the output binary and not generated at all. /// </summary> public bool EmitPdbFile => EmitPdb && EmitOptions.DebugInformationFormat != DebugInformationFormat.Embedded; #region Metadata References /// <summary> /// Resolves metadata references stored in <see cref="MetadataReferences"/> using given file resolver and metadata provider. /// </summary> /// <param name="metadataResolver"><see cref="MetadataReferenceResolver"/> to use for assembly name and relative path resolution.</param> /// <returns>Yields resolved metadata references or <see cref="UnresolvedMetadataReference"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="metadataResolver"/> is null.</exception> public IEnumerable<MetadataReference> ResolveMetadataReferences(MetadataReferenceResolver metadataResolver) { if (metadataResolver == null) { throw new ArgumentNullException(nameof(metadataResolver)); } return ResolveMetadataReferences(metadataResolver, diagnosticsOpt: null, messageProviderOpt: null); } /// <summary> /// Resolves metadata references stored in <see cref="MetadataReferences"/> using given file resolver and metadata provider. /// If a non-null diagnostic bag <paramref name="diagnosticsOpt"/> is provided, it catches exceptions that may be generated while reading the metadata file and /// reports appropriate diagnostics. /// Otherwise, if <paramref name="diagnosticsOpt"/> is null, the exceptions are unhandled. /// </summary> /// <remarks> /// called by CommonCompiler with diagnostics and message provider /// </remarks> internal IEnumerable<MetadataReference> ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) { RoslynDebug.Assert(metadataResolver != null); var resolved = new List<MetadataReference>(); this.ResolveMetadataReferences(metadataResolver, diagnosticsOpt, messageProviderOpt, resolved); return resolved; } internal virtual bool ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt, List<MetadataReference> resolved) { bool result = true; foreach (CommandLineReference cmdReference in MetadataReferences) { var references = ResolveMetadataReference(cmdReference, metadataResolver, diagnosticsOpt, messageProviderOpt); if (!references.IsDefaultOrEmpty) { resolved.AddRange(references); } else { result = false; if (diagnosticsOpt == null) { // no diagnostic, so leaved unresolved reference in list resolved.Add(new UnresolvedMetadataReference(cmdReference.Reference, cmdReference.Properties)); } } } return result; } internal static ImmutableArray<PortableExecutableReference> ResolveMetadataReference(CommandLineReference cmdReference, MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) { RoslynDebug.Assert(metadataResolver != null); Debug.Assert((diagnosticsOpt == null) == (messageProviderOpt == null)); ImmutableArray<PortableExecutableReference> references; try { references = metadataResolver.ResolveReference(cmdReference.Reference, baseFilePath: null, properties: cmdReference.Properties); } catch (Exception e) when (diagnosticsOpt != null && (e is BadImageFormatException || e is IOException)) { var diagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProviderOpt!, Location.None, cmdReference.Reference, cmdReference.Properties.Kind); diagnosticsOpt.Add(((DiagnosticWithInfo)diagnostic).Info); return ImmutableArray<PortableExecutableReference>.Empty; } if (references.IsDefaultOrEmpty && diagnosticsOpt != null) { RoslynDebug.AssertNotNull(messageProviderOpt); diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.ERR_MetadataFileNotFound, cmdReference.Reference)); return ImmutableArray<PortableExecutableReference>.Empty; } return references; } #endregion #region Analyzer References /// <summary> /// Resolves analyzer references stored in <see cref="AnalyzerReferences"/> using given file resolver. /// </summary> /// <param name="analyzerLoader">Load an assembly from a file path</param> /// <returns>Yields resolved <see cref="AnalyzerFileReference"/> or <see cref="UnresolvedAnalyzerReference"/>.</returns> public IEnumerable<AnalyzerReference> ResolveAnalyzerReferences(IAnalyzerAssemblyLoader analyzerLoader) { foreach (CommandLineAnalyzerReference cmdLineReference in AnalyzerReferences) { yield return ResolveAnalyzerReference(cmdLineReference, analyzerLoader) ?? (AnalyzerReference)new UnresolvedAnalyzerReference(cmdLineReference.FilePath); } } internal void ResolveAnalyzersFromArguments( string language, List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, IAnalyzerAssemblyLoader analyzerLoader, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { var analyzerBuilder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); var generatorBuilder = ImmutableArray.CreateBuilder<ISourceGenerator>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => { var analyzerReference = o as AnalyzerFileReference; RoslynDebug.Assert(analyzerReference is object); DiagnosticInfo? diagnostic; switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_UnableToLoadAnalyzer, analyzerReference.FullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerCannotBeCreated, e.TypeName ?? "", analyzerReference.FullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_NoAnalyzerInAssembly, analyzerReference.FullPath); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerReferencesFramework, analyzerReference.FullPath, e.TypeName!); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.None: default: return; } // Filter this diagnostic based on the compilation options so that /nowarn and /warnaserror etc. take effect. diagnostic = messageProvider.FilterDiagnosticInfo(diagnostic, this.CompilationOptions); if (diagnostic != null) { diagnostics.Add(diagnostic); } }; var resolvedReferences = ArrayBuilder<AnalyzerFileReference>.GetInstance(); foreach (var reference in AnalyzerReferences) { var resolvedReference = ResolveAnalyzerReference(reference, analyzerLoader); if (resolvedReference != null) { resolvedReferences.Add(resolvedReference); // register the reference to the analyzer loader: analyzerLoader.AddDependencyLocation(resolvedReference.FullPath); } else { diagnostics.Add(new DiagnosticInfo(messageProvider, messageProvider.ERR_MetadataFileNotFound, reference.FilePath)); } } // All analyzer references are registered now, we can start loading them: foreach (var resolvedReference in resolvedReferences) { resolvedReference.AnalyzerLoadFailed += errorHandler; if (!skipAnalyzers) resolvedReference.AddAnalyzers(analyzerBuilder, language); resolvedReference.AddGenerators(generatorBuilder, language); resolvedReference.AnalyzerLoadFailed -= errorHandler; } resolvedReferences.Free(); generators = generatorBuilder.ToImmutable(); analyzers = analyzerBuilder.ToImmutable(); } private AnalyzerFileReference? ResolveAnalyzerReference(CommandLineAnalyzerReference reference, IAnalyzerAssemblyLoader analyzerLoader) { string? resolvedPath = FileUtilities.ResolveRelativePath(reference.FilePath, basePath: null, baseDirectory: BaseDirectory, searchPaths: ReferencePaths, fileExists: File.Exists); if (resolvedPath != null) { resolvedPath = FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } if (resolvedPath != null) { return new AnalyzerFileReference(resolvedPath, analyzerLoader); } return null; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The base class for representing command line arguments to a /// <see cref="CommonCompiler"/>. /// </summary> public abstract class CommandLineArguments { internal bool IsScriptRunner { get; set; } /// <summary> /// Drop to an interactive loop. If a script is specified in <see cref="SourceFiles"/> executes the script first. /// </summary> public bool InteractiveMode { get; internal set; } /// <summary> /// Directory used to resolve relative paths stored in the arguments. /// </summary> /// <remarks> /// Except for paths stored in <see cref="MetadataReferences"/>, all /// paths stored in the properties of this class are resolved and /// absolute. This is the directory that relative paths specified on /// command line were resolved against. /// </remarks> public string? BaseDirectory { get; internal set; } /// <summary> /// A list of pairs of paths. This stores the value of the command-line compiler /// option /pathMap:X1=Y1;X2=Y2... which causes a prefix of X1 followed by a path /// separator to be replaced by Y1 followed by a path separator, and so on for each following pair. /// </summary> /// <remarks> /// This option is used to help get build-to-build determinism even when the build /// directory is different from one build to the next. The prefix matching is case sensitive. /// </remarks> public ImmutableArray<KeyValuePair<string, string>> PathMap { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for references. /// </summary> public ImmutableArray<string> ReferencePaths { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for sources specified as #load directives. /// </summary> public ImmutableArray<string> SourcePaths { get; internal set; } /// <summary> /// Sequence of absolute paths used to search for key files. /// </summary> public ImmutableArray<string> KeyFileSearchPaths { get; internal set; } /// <summary> /// If true, use UTF8 for output. /// </summary> public bool Utf8Output { get; internal set; } /// <summary> /// Compilation name or null if not specified. /// </summary> public string? CompilationName { get; internal set; } /// <summary> /// Gets the emit options. /// </summary> public EmitOptions EmitOptions { get; internal set; } = null!; // initialized by Parse /// <summary> /// Name of the output file or null if not specified. /// </summary> public string? OutputFileName { get; internal set; } /// <summary> /// Path of the output ref assembly or null if not specified. /// </summary> public string? OutputRefFilePath { get; internal set; } /// <summary> /// Path of the PDB file or null if same as output binary path with .pdb extension. /// </summary> public string? PdbPath { get; internal set; } /// <summary> /// Path of the file containing information linking the compilation to source server that stores /// a snapshot of the source code included in the compilation. /// </summary> public string? SourceLink { get; internal set; } /// <summary> /// Absolute path of the .ruleset file or null if not specified. /// </summary> public string? RuleSetPath { get; internal set; } /// <summary> /// True to emit PDB information (to a standalone PDB file or embedded into the PE file). /// </summary> public bool EmitPdb { get; internal set; } /// <summary> /// Absolute path of the output directory (could only be null if there is an error reported). /// </summary> public string OutputDirectory { get; internal set; } = null!; // initialized by Parse /// <summary> /// Absolute path of the documentation comment XML file or null if not specified. /// </summary> public string? DocumentationPath { get; internal set; } /// <summary> /// Absolute path of the directory to place generated files in, or <c>null</c> to not emit any generated files. /// </summary> public string? GeneratedFilesOutputDirectory { get; internal set; } /// <summary> /// Options controlling the generation of a SARIF log file containing compilation or /// analysis diagnostics, or null if no log file is desired. /// </summary> public ErrorLogOptions? ErrorLogOptions { get; internal set; } /// <summary> /// Options controlling the generation of a SARIF log file containing compilation or /// analysis diagnostics, or null if no log file is desired. /// </summary> public string? ErrorLogPath => ErrorLogOptions?.Path; /// <summary> /// An absolute path of the app.config file or null if not specified. /// </summary> public string? AppConfigPath { get; internal set; } /// <summary> /// Errors while parsing the command line arguments. /// </summary> public ImmutableArray<Diagnostic> Errors { get; internal set; } /// <summary> /// References to metadata supplied on the command line. /// Includes assemblies specified via /r and netmodules specified via /addmodule. /// </summary> public ImmutableArray<CommandLineReference> MetadataReferences { get; internal set; } /// <summary> /// References to analyzers supplied on the command line. /// </summary> public ImmutableArray<CommandLineAnalyzerReference> AnalyzerReferences { get; internal set; } /// <summary> /// A set of paths to EditorConfig-compatible analyzer config files. /// </summary> public ImmutableArray<string> AnalyzerConfigPaths { get; internal set; } /// <summary> /// A set of additional non-code text files that can be used by analyzers. /// </summary> public ImmutableArray<CommandLineSourceFile> AdditionalFiles { get; internal set; } /// <summary> /// A set of files to embed in the PDB. /// </summary> public ImmutableArray<CommandLineSourceFile> EmbeddedFiles { get; internal set; } /// <value> /// Report additional information related to analyzers, such as analyzer execution time. /// </value> public bool ReportAnalyzer { get; internal set; } /// <value> /// Skip execution of <see cref="DiagnosticAnalyzer"/>s. /// </value> public bool SkipAnalyzers { get; internal set; } /// <summary> /// If true, prepend the command line header logo during /// <see cref="CommonCompiler.Run"/>. /// </summary> public bool DisplayLogo { get; internal set; } /// <summary> /// If true, append the command line help during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayHelp { get; internal set; } /// <summary> /// If true, append the compiler version during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayVersion { get; internal set; } /// <summary> /// If true, prepend the compiler-supported language versions during /// <see cref="CommonCompiler.Run"/> /// </summary> public bool DisplayLangVersions { get; internal set; } /// <summary> /// The path to a Win32 resource. /// </summary> public string? Win32ResourceFile { get; internal set; } /// <summary> /// The path to a .ico icon file. /// </summary> public string? Win32Icon { get; internal set; } /// <summary> /// The path to a Win32 manifest file to embed /// into the output portable executable (PE) file. /// </summary> public string? Win32Manifest { get; internal set; } /// <summary> /// If true, do not embed any Win32 manifest, including /// one specified by <see cref="Win32Manifest"/> or any /// default manifest. /// </summary> public bool NoWin32Manifest { get; internal set; } /// <summary> /// Resources specified as arguments to the compilation. /// </summary> public ImmutableArray<ResourceDescription> ManifestResources { get; internal set; } /// <summary> /// Encoding to be used for source files or 'null' for autodetect/default. /// </summary> public Encoding? Encoding { get; internal set; } /// <summary> /// Hash algorithm to use to calculate source file debug checksums and PDB checksum. /// </summary> public SourceHashAlgorithm ChecksumAlgorithm { get; internal set; } /// <summary> /// Arguments following a script file or separator "--". Null if the command line parser is not interactive. /// </summary> public ImmutableArray<string> ScriptArguments { get; internal set; } /// <summary> /// Source file paths. /// </summary> /// <remarks> /// Includes files specified directly on command line as well as files matching patterns specified /// on command line using '*' and '?' wildcards or /recurse option. /// </remarks> public ImmutableArray<CommandLineSourceFile> SourceFiles { get; internal set; } /// <summary> /// Full path of a log of file paths accessed by the compiler, or null if file logging should be suppressed. /// </summary> /// <remarks> /// Two log files will be created: /// One with path <see cref="TouchedFilesPath"/> and extension ".read" logging the files read, /// and second with path <see cref="TouchedFilesPath"/> and extension ".write" logging the files written to during compilation. /// </remarks> public string? TouchedFilesPath { get; internal set; } /// <summary> /// If true, prints the full path of the file containing errors or /// warnings in diagnostics. /// </summary> public bool PrintFullPaths { get; internal set; } /// <summary> /// Options to the <see cref="CommandLineParser"/>. /// </summary> /// <returns></returns> public ParseOptions ParseOptions { get { return ParseOptionsCore; } } /// <summary> /// Options to the <see cref="Compilation"/>. /// </summary> public CompilationOptions CompilationOptions { get { return CompilationOptionsCore; } } protected abstract ParseOptions ParseOptionsCore { get; } protected abstract CompilationOptions CompilationOptionsCore { get; } /// <summary> /// Specify the preferred output language name. /// </summary> public CultureInfo? PreferredUILang { get; internal set; } internal StrongNameProvider GetStrongNameProvider(StrongNameFileSystem fileSystem) => new DesktopStrongNameProvider(KeyFileSearchPaths, fileSystem); internal CommandLineArguments() { } /// <summary> /// Returns a full path of the file that the compiler will generate the assembly to if compilation succeeds. /// </summary> /// <remarks> /// The method takes <paramref name="outputFileName"/> rather than using the value of <see cref="OutputFileName"/> /// since the latter might be unspecified, in which case actual output path can't be determined for C# command line /// without creating a compilation and finding an entry point. VB does not allow <see cref="OutputFileName"/> to /// be unspecified. /// </remarks> public string GetOutputFilePath(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException(nameof(outputFileName)); } return Path.Combine(OutputDirectory, outputFileName); } /// <summary> /// Returns a full path of the PDB file that the compiler will generate the debug symbols to /// if <see cref="EmitPdbFile"/> is true and the compilation succeeds. /// </summary> /// <remarks> /// The method takes <paramref name="outputFileName"/> rather than using the value of <see cref="OutputFileName"/> /// since the latter might be unspecified, in which case actual output path can't be determined for C# command line /// without creating a compilation and finding an entry point. VB does not allow <see cref="OutputFileName"/> to /// be unspecified. /// </remarks> public string GetPdbFilePath(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException(nameof(outputFileName)); } return PdbPath ?? Path.Combine(OutputDirectory, Path.ChangeExtension(outputFileName, ".pdb")); } /// <summary> /// Returns true if the PDB is generated to a PDB file, as opposed to embedded to the output binary and not generated at all. /// </summary> public bool EmitPdbFile => EmitPdb && EmitOptions.DebugInformationFormat != DebugInformationFormat.Embedded; #region Metadata References /// <summary> /// Resolves metadata references stored in <see cref="MetadataReferences"/> using given file resolver and metadata provider. /// </summary> /// <param name="metadataResolver"><see cref="MetadataReferenceResolver"/> to use for assembly name and relative path resolution.</param> /// <returns>Yields resolved metadata references or <see cref="UnresolvedMetadataReference"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="metadataResolver"/> is null.</exception> public IEnumerable<MetadataReference> ResolveMetadataReferences(MetadataReferenceResolver metadataResolver) { if (metadataResolver == null) { throw new ArgumentNullException(nameof(metadataResolver)); } return ResolveMetadataReferences(metadataResolver, diagnosticsOpt: null, messageProviderOpt: null); } /// <summary> /// Resolves metadata references stored in <see cref="MetadataReferences"/> using given file resolver and metadata provider. /// If a non-null diagnostic bag <paramref name="diagnosticsOpt"/> is provided, it catches exceptions that may be generated while reading the metadata file and /// reports appropriate diagnostics. /// Otherwise, if <paramref name="diagnosticsOpt"/> is null, the exceptions are unhandled. /// </summary> /// <remarks> /// called by CommonCompiler with diagnostics and message provider /// </remarks> internal IEnumerable<MetadataReference> ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) { RoslynDebug.Assert(metadataResolver != null); var resolved = new List<MetadataReference>(); this.ResolveMetadataReferences(metadataResolver, diagnosticsOpt, messageProviderOpt, resolved); return resolved; } internal virtual bool ResolveMetadataReferences(MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt, List<MetadataReference> resolved) { bool result = true; foreach (CommandLineReference cmdReference in MetadataReferences) { var references = ResolveMetadataReference(cmdReference, metadataResolver, diagnosticsOpt, messageProviderOpt); if (!references.IsDefaultOrEmpty) { resolved.AddRange(references); } else { result = false; if (diagnosticsOpt == null) { // no diagnostic, so leaved unresolved reference in list resolved.Add(new UnresolvedMetadataReference(cmdReference.Reference, cmdReference.Properties)); } } } return result; } internal static ImmutableArray<PortableExecutableReference> ResolveMetadataReference(CommandLineReference cmdReference, MetadataReferenceResolver metadataResolver, List<DiagnosticInfo>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt) { RoslynDebug.Assert(metadataResolver != null); Debug.Assert((diagnosticsOpt == null) == (messageProviderOpt == null)); ImmutableArray<PortableExecutableReference> references; try { references = metadataResolver.ResolveReference(cmdReference.Reference, baseFilePath: null, properties: cmdReference.Properties); } catch (Exception e) when (diagnosticsOpt != null && (e is BadImageFormatException || e is IOException)) { var diagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProviderOpt!, Location.None, cmdReference.Reference, cmdReference.Properties.Kind); diagnosticsOpt.Add(((DiagnosticWithInfo)diagnostic).Info); return ImmutableArray<PortableExecutableReference>.Empty; } if (references.IsDefaultOrEmpty && diagnosticsOpt != null) { RoslynDebug.AssertNotNull(messageProviderOpt); diagnosticsOpt.Add(new DiagnosticInfo(messageProviderOpt, messageProviderOpt.ERR_MetadataFileNotFound, cmdReference.Reference)); return ImmutableArray<PortableExecutableReference>.Empty; } return references; } #endregion #region Analyzer References /// <summary> /// Resolves analyzer references stored in <see cref="AnalyzerReferences"/> using given file resolver. /// </summary> /// <param name="analyzerLoader">Load an assembly from a file path</param> /// <returns>Yields resolved <see cref="AnalyzerFileReference"/> or <see cref="UnresolvedAnalyzerReference"/>.</returns> public IEnumerable<AnalyzerReference> ResolveAnalyzerReferences(IAnalyzerAssemblyLoader analyzerLoader) { foreach (CommandLineAnalyzerReference cmdLineReference in AnalyzerReferences) { yield return ResolveAnalyzerReference(cmdLineReference, analyzerLoader) ?? (AnalyzerReference)new UnresolvedAnalyzerReference(cmdLineReference.FilePath); } } internal void ResolveAnalyzersFromArguments( string language, List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, IAnalyzerAssemblyLoader analyzerLoader, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { var analyzerBuilder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); var generatorBuilder = ImmutableArray.CreateBuilder<ISourceGenerator>(); EventHandler<AnalyzerLoadFailureEventArgs> errorHandler = (o, e) => { var analyzerReference = o as AnalyzerFileReference; RoslynDebug.Assert(analyzerReference is object); DiagnosticInfo? diagnostic; switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_UnableToLoadAnalyzer, analyzerReference.FullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerCannotBeCreated, e.TypeName ?? "", analyzerReference.FullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_NoAnalyzerInAssembly, analyzerReference.FullPath); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: diagnostic = new DiagnosticInfo(messageProvider, messageProvider.WRN_AnalyzerReferencesFramework, analyzerReference.FullPath, e.TypeName!); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.None: default: return; } // Filter this diagnostic based on the compilation options so that /nowarn and /warnaserror etc. take effect. diagnostic = messageProvider.FilterDiagnosticInfo(diagnostic, this.CompilationOptions); if (diagnostic != null) { diagnostics.Add(diagnostic); } }; var resolvedReferences = ArrayBuilder<AnalyzerFileReference>.GetInstance(); foreach (var reference in AnalyzerReferences) { var resolvedReference = ResolveAnalyzerReference(reference, analyzerLoader); if (resolvedReference != null) { resolvedReferences.Add(resolvedReference); // register the reference to the analyzer loader: analyzerLoader.AddDependencyLocation(resolvedReference.FullPath); } else { diagnostics.Add(new DiagnosticInfo(messageProvider, messageProvider.ERR_MetadataFileNotFound, reference.FilePath)); } } // All analyzer references are registered now, we can start loading them. foreach (var resolvedReference in resolvedReferences) { resolvedReference.AnalyzerLoadFailed += errorHandler; resolvedReference.AddAnalyzers(analyzerBuilder, language, shouldIncludeAnalyzer); resolvedReference.AddGenerators(generatorBuilder, language); resolvedReference.AnalyzerLoadFailed -= errorHandler; } resolvedReferences.Free(); generators = generatorBuilder.ToImmutable(); analyzers = analyzerBuilder.ToImmutable(); // If we are skipping analyzers, ensure that we only add suppressors. bool shouldIncludeAnalyzer(DiagnosticAnalyzer analyzer) => !skipAnalyzers || analyzer is DiagnosticSuppressor; } private AnalyzerFileReference? ResolveAnalyzerReference(CommandLineAnalyzerReference reference, IAnalyzerAssemblyLoader analyzerLoader) { string? resolvedPath = FileUtilities.ResolveRelativePath(reference.FilePath, basePath: null, baseDirectory: BaseDirectory, searchPaths: ReferencePaths, fileExists: File.Exists); if (resolvedPath != null) { resolvedPath = FileUtilities.TryNormalizeAbsolutePath(resolvedPath); } if (resolvedPath != null) { return new AnalyzerFileReference(resolvedPath, analyzerLoader); } return null; } #endregion } }
1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerFileReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents analyzers stored in an analyzer assembly file. /// </summary> /// <remarks> /// Analyzer are read from the file, owned by the reference, and doesn't change /// since the reference is accessed until the reference object is garbage collected. /// /// If you need to manage the lifetime of the analyzer reference (and the file stream) explicitly use <see cref="AnalyzerImageReference"/>. /// </remarks> public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable<AnalyzerReference> { private delegate IEnumerable<string> AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); public override string FullPath { get; } private readonly IAnalyzerAssemblyLoader _assemblyLoader; private readonly Extensions<DiagnosticAnalyzer> _diagnosticAnalyzers; private readonly Extensions<ISourceGenerator> _generators; private string? _lazyDisplay; private object? _lazyIdentity; private Assembly? _lazyAssembly; public event EventHandler<AnalyzerLoadFailureEventArgs>? AnalyzerLoadFailed; /// <summary> /// Creates an AnalyzerFileReference with the given <paramref name="fullPath"/> and <paramref name="assemblyLoader"/>. /// </summary> /// <param name="fullPath">Full path of the analyzer assembly.</param> /// <param name="assemblyLoader">Loader for obtaining the <see cref="Assembly"/> from the <paramref name="fullPath"/></param> public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLoader) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); FullPath = fullPath; _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); _diagnosticAnalyzers = new(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); _generators = new(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false, coerceFunction: CoerceGeneratorType); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. assemblyLoader.AddDependencyLocation(fullPath); } public IAnalyzerAssemblyLoader AssemblyLoader => _assemblyLoader; public override bool Equals(object? obj) => Equals(obj as AnalyzerFileReference); public bool Equals(AnalyzerFileReference? other) { if (ReferenceEquals(this, other)) { return true; } return other is object && ReferenceEquals(_assemblyLoader, other._assemblyLoader) && FullPath == other.FullPath; } // legacy, for backwards compat: public bool Equals(AnalyzerReference? other) { if (ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } if (other is AnalyzerFileReference fileReference) { return Equals(fileReference); } return FullPath == other.FullPath; } public override int GetHashCode() => Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode()); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { // This API returns duplicates of analyzers that support multiple languages. // We explicitly retain this behaviour to ensure back compat return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return _diagnosticAnalyzers.GetExtensions(language); } public override ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() { return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); } [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public override ImmutableArray<ISourceGenerator> GetGenerators() { return _generators.GetExtensions(LanguageNames.CSharp); } public override ImmutableArray<ISourceGenerator> GetGenerators(string language) { return _generators.GetExtensions(language); } public override string Display { get { if (_lazyDisplay == null) { InitializeDisplayAndId(); } return _lazyDisplay; } } public override object Id { get { if (_lazyIdentity == null) { InitializeDisplayAndId(); } return _lazyIdentity; } } [MemberNotNull(nameof(_lazyIdentity), nameof(_lazyDisplay))] private void InitializeDisplayAndId() { try { // AssemblyName.GetAssemblyName(path) is not available on CoreCLR. // Use our metadata reader to do the equivalent thing. using var reader = new PEReader(FileUtilities.OpenRead(FullPath)); var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); _lazyDisplay = assemblyIdentity.Name; _lazyIdentity = assemblyIdentity; } catch { _lazyDisplay = FileNameUtilities.GetFileName(FullPath, includeExtension: false); _lazyIdentity = _lazyDisplay; } } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="DiagnosticAnalyzer"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddAnalyzers(ImmutableArray<DiagnosticAnalyzer>.Builder builder, string language) { _diagnosticAnalyzers.AddExtensions(builder, language); } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="ISourceGenerator"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddGenerators(ImmutableArray<ISourceGenerator>.Builder builder, string language) { _generators.AddExtensions(builder, language); } private static AnalyzerLoadFailureEventArgs CreateAnalyzerFailedArgs(Exception e, string? typeName = null) { // unwrap: e = (e as TargetInvocationException) ?? e; // remove all line breaks from the exception message string message = e.Message.Replace("\r", "").Replace("\n", ""); var errorCode = (typeName != null) ? AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer : AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer; return new AnalyzerLoadFailureEventArgs(errorCode, message, e, typeName); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap() { return _diagnosticAnalyzers.GetExtensionTypeNameMap(); } /// <summary> /// Opens the analyzer dll with the metadata reader and builds a map of language -> analyzer type names. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata.</exception> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30449")] private static ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); // This is longer than strictly necessary to avoid thrashing the GC with string allocations // in the call to GetFullyQualifiedTypeNames. Specifically, this checks for the presence of // supported languages prior to creating the type names. var typeNameMap = from module in assembly.GetModules() from typeDefHandle in module.MetadataReader.TypeDefinitions let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) where supportedLanguages.Any() let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) from supportedLanguage in supportedLanguages group typeName by supportedLanguage; return typeNameMap.ToImmutableSortedDictionary(g => g.Key, g => g.ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); } private static IEnumerable<string> GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) { IEnumerable<string>? result = null; foreach (CustomAttributeHandle customAttrHandle in typeDef.GetCustomAttributes()) { if (peModule.IsTargetAttribute(customAttrHandle, attributeType.Namespace!, attributeType.Name, ctor: out _)) { if (languagesFunc(peModule, customAttrHandle) is { } attributeSupportedLanguages) { if (result is null) { result = attributeSupportedLanguages; } else { // This is a slow path, but only occurs if a single type has multiple // DiagnosticAnalyzerAttribute instances applied to it. result = result.Concat(attributeSupportedLanguages); } } } } return result ?? SpecializedCollections.EmptyEnumerable<string>(); } private static IEnumerable<string> GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The DiagnosticAnalyzerAttribute has one constructor, which has a string parameter for the // first supported language and an array parameter for additional supported languages. // Parse the argument blob to extract the languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); return ReadLanguagesFromAttribute(ref argsReader); } private static IEnumerable<string> GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The GeneratorAttribute has two constructors: one default, and one with a string parameter for the // first supported language and an array parameter for additional supported languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); if (argsReader.Length == 4) { // default ctor return ImmutableArray.Create(LanguageNames.CSharp); } else { // Parse the argument blob to extract the languages. return ReadLanguagesFromAttribute(ref argsReader); } } // https://github.com/dotnet/roslyn/issues/53994 tracks re-enabling nullable and fixing this method #nullable disable private static IEnumerable<string> ReadLanguagesFromAttribute(ref BlobReader argsReader) { if (argsReader.Length > 4) { // Arguments are present--check prologue. if (argsReader.ReadByte() == 1 && argsReader.ReadByte() == 0) { string firstLanguageName; if (!PEModule.CrackStringInAttributeValue(out firstLanguageName, ref argsReader)) { return SpecializedCollections.EmptyEnumerable<string>(); } ImmutableArray<string> additionalLanguageNames; if (PEModule.CrackStringArrayInAttributeValue(out additionalLanguageNames, ref argsReader)) { if (additionalLanguageNames.Length == 0) { return SpecializedCollections.SingletonEnumerable(firstLanguageName); } return additionalLanguageNames.Insert(0, firstLanguageName); } } } return SpecializedCollections.EmptyEnumerable<string>(); } #nullable enable private static ISourceGenerator? CoerceGeneratorType(object? generator) { if (generator is IIncrementalGenerator incrementalGenerator) { return new IncrementalGeneratorWrapper(incrementalGenerator); } return null; } private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) { var declaringType = typeDef.GetDeclaringType(); // Non nested type - simply get the full name if (declaringType.IsNil) { return peModule.GetFullNameOrThrow(typeDef.Namespace, typeDef.Name); } else { var declaringTypeDef = peModule.MetadataReader.GetTypeDefinition(declaringType); return GetFullyQualifiedTypeName(declaringTypeDef, peModule) + "+" + peModule.MetadataReader.GetString(typeDef.Name); } } private sealed class Extensions<TExtension> where TExtension : class { private readonly AnalyzerFileReference _reference; private readonly Type _attributeType; private readonly AttributeLanguagesFunc _languagesFunc; private readonly bool _allowNetFramework; private readonly Func<object?, TExtension?>? _coerceFunction; private ImmutableArray<TExtension> _lazyAllExtensions; private ImmutableDictionary<string, ImmutableArray<TExtension>> _lazyExtensionsPerLanguage; private ImmutableSortedDictionary<string, ImmutableSortedSet<string>>? _lazyExtensionTypeNameMap; internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework, Func<object?, TExtension?>? coerceFunction = null) { _reference = reference; _attributeType = attributeType; _languagesFunc = languagesFunc; _allowNetFramework = allowNetFramework; _coerceFunction = coerceFunction; _lazyAllExtensions = default; _lazyExtensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } internal ImmutableArray<TExtension> GetExtensionsForAllLanguages(bool includeDuplicates) { if (_lazyAllExtensions.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); } return _lazyAllExtensions; } private static ImmutableArray<TExtension> CreateExtensionsForAllLanguages(Extensions<TExtension> extensions, bool includeDuplicates) { // Get all analyzers in the assembly. var map = ImmutableSortedDictionary.CreateBuilder<string, ImmutableArray<TExtension>>(StringComparer.OrdinalIgnoreCase); extensions.AddExtensions(map); var builder = ImmutableArray.CreateBuilder<TExtension>(); foreach (var analyzers in map.Values) { foreach (var analyzer in analyzers) { builder.Add(analyzer); } } if (includeDuplicates) { return builder.ToImmutable(); } else { return builder.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); } } private class ExtTypeComparer : IEqualityComparer<TExtension> { public static readonly ExtTypeComparer Instance = new(); public bool Equals(TExtension? x, TExtension? y) => object.Equals(x?.GetType(), y?.GetType()); public int GetHashCode(TExtension obj) => obj.GetType().GetHashCode(); } internal ImmutableArray<TExtension> GetExtensions(string language) { if (string.IsNullOrEmpty(language)) { throw new ArgumentException("language"); } return ImmutableInterlocked.GetOrAdd(ref _lazyExtensionsPerLanguage, language, CreateLanguageSpecificExtensions, this); } private static ImmutableArray<TExtension> CreateLanguageSpecificExtensions(string language, Extensions<TExtension> extensions) { // Get all analyzers in the assembly for the given language. var builder = ImmutableArray.CreateBuilder<TExtension>(); extensions.AddExtensions(builder, language); return builder.ToImmutable(); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetExtensionTypeNameMap() { if (_lazyExtensionTypeNameMap == null) { var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } return _lazyExtensionTypeNameMap; } internal void AddExtensions(ImmutableSortedDictionary<string, ImmutableArray<TExtension>>.Builder builder) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); if (analyzerTypeNameMap.Count == 0) { return; } analyzerAssembly = _reference.GetAssembly(); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. foreach (var (language, _) in analyzerTypeNameMap) { if (language == null) { continue; } var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.Add(language, analyzers); } // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } internal void AddExtensions(ImmutableArray<TExtension>.Builder builder, string language) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); // If there are no analyzers, don't load the assembly at all. if (!analyzerTypeNameMap.ContainsKey(language)) { return; } analyzerAssembly = _reference.GetAssembly(); if (analyzerAssembly == null) { // This can be null if NoOpAnalyzerAssemblyLoader is used. return; } } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.AddRange(analyzers); // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } private ImmutableArray<TExtension> GetLanguageSpecificAnalyzers(Assembly analyzerAssembly, ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap, string language, ref bool reportedError) { ImmutableSortedSet<string>? languageSpecificAnalyzerTypeNames; if (!analyzerTypeNameMap.TryGetValue(language, out languageSpecificAnalyzerTypeNames)) { return ImmutableArray<TExtension>.Empty; } return this.GetAnalyzersForTypeNames(analyzerAssembly, languageSpecificAnalyzerTypeNames, ref reportedError); } private ImmutableArray<TExtension> GetAnalyzersForTypeNames(Assembly analyzerAssembly, IEnumerable<string> analyzerTypeNames, ref bool reportedError) { var analyzers = ImmutableArray.CreateBuilder<TExtension>(); // Given the type names, get the actual System.Type and try to create an instance of the type through reflection. foreach (var typeName in analyzerTypeNames) { Type? type; try { type = analyzerAssembly.GetType(typeName, throwOnError: true, ignoreCase: false); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } Debug.Assert(type != null); // check if this references net framework, and issue a diagnostic that this isn't supported if (!_allowNetFramework) { var targetFrameworkAttribute = analyzerAssembly.GetCustomAttribute<TargetFrameworkAttribute>(); if (targetFrameworkAttribute is object && targetFrameworkAttribute.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase)) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs( AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, string.Format(CodeAnalysisResources.AssemblyReferencesNetFramework, typeName), typeNameOpt: typeName)); continue; } } object? typeInstance; try { typeInstance = Activator.CreateInstance(type); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } TExtension? analyzer = typeInstance as TExtension ?? _coerceFunction?.Invoke(typeInstance); if (analyzer != null) { analyzers.Add(analyzer); } } return analyzers.ToImmutable(); } } public Assembly GetAssembly() { if (_lazyAssembly == null) { _lazyAssembly = _assemblyLoader.LoadFromPath(FullPath); } return _lazyAssembly; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents analyzers stored in an analyzer assembly file. /// </summary> /// <remarks> /// Analyzer are read from the file, owned by the reference, and doesn't change /// since the reference is accessed until the reference object is garbage collected. /// /// If you need to manage the lifetime of the analyzer reference (and the file stream) explicitly use <see cref="AnalyzerImageReference"/>. /// </remarks> public sealed class AnalyzerFileReference : AnalyzerReference, IEquatable<AnalyzerReference> { private delegate IEnumerable<string> AttributeLanguagesFunc(PEModule module, CustomAttributeHandle attribute); public override string FullPath { get; } private readonly IAnalyzerAssemblyLoader _assemblyLoader; private readonly Extensions<DiagnosticAnalyzer> _diagnosticAnalyzers; private readonly Extensions<ISourceGenerator> _generators; private string? _lazyDisplay; private object? _lazyIdentity; private Assembly? _lazyAssembly; public event EventHandler<AnalyzerLoadFailureEventArgs>? AnalyzerLoadFailed; /// <summary> /// Creates an AnalyzerFileReference with the given <paramref name="fullPath"/> and <paramref name="assemblyLoader"/>. /// </summary> /// <param name="fullPath">Full path of the analyzer assembly.</param> /// <param name="assemblyLoader">Loader for obtaining the <see cref="Assembly"/> from the <paramref name="fullPath"/></param> public AnalyzerFileReference(string fullPath, IAnalyzerAssemblyLoader assemblyLoader) { CompilerPathUtilities.RequireAbsolutePath(fullPath, nameof(fullPath)); FullPath = fullPath; _assemblyLoader = assemblyLoader ?? throw new ArgumentNullException(nameof(assemblyLoader)); _diagnosticAnalyzers = new(this, typeof(DiagnosticAnalyzerAttribute), GetDiagnosticsAnalyzerSupportedLanguages, allowNetFramework: true); _generators = new(this, typeof(GeneratorAttribute), GetGeneratorSupportedLanguages, allowNetFramework: false, coerceFunction: CoerceGeneratorType); // Note this analyzer full path as a dependency location, so that the analyzer loader // can correctly load analyzer dependencies. assemblyLoader.AddDependencyLocation(fullPath); } public IAnalyzerAssemblyLoader AssemblyLoader => _assemblyLoader; public override bool Equals(object? obj) => Equals(obj as AnalyzerFileReference); public bool Equals(AnalyzerFileReference? other) { if (ReferenceEquals(this, other)) { return true; } return other is object && ReferenceEquals(_assemblyLoader, other._assemblyLoader) && FullPath == other.FullPath; } // legacy, for backwards compat: public bool Equals(AnalyzerReference? other) { if (ReferenceEquals(this, other)) { return true; } if (other is null) { return false; } if (other is AnalyzerFileReference fileReference) { return Equals(fileReference); } return FullPath == other.FullPath; } public override int GetHashCode() => Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode()); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() { // This API returns duplicates of analyzers that support multiple languages. // We explicitly retain this behaviour to ensure back compat return _diagnosticAnalyzers.GetExtensionsForAllLanguages(includeDuplicates: true); } public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) { return _diagnosticAnalyzers.GetExtensions(language); } public override ImmutableArray<ISourceGenerator> GetGeneratorsForAllLanguages() { return _generators.GetExtensionsForAllLanguages(includeDuplicates: false); } [Obsolete("Use GetGenerators(string language) or GetGeneratorsForAllLanguages()")] public override ImmutableArray<ISourceGenerator> GetGenerators() { return _generators.GetExtensions(LanguageNames.CSharp); } public override ImmutableArray<ISourceGenerator> GetGenerators(string language) { return _generators.GetExtensions(language); } public override string Display { get { if (_lazyDisplay == null) { InitializeDisplayAndId(); } return _lazyDisplay; } } public override object Id { get { if (_lazyIdentity == null) { InitializeDisplayAndId(); } return _lazyIdentity; } } [MemberNotNull(nameof(_lazyIdentity), nameof(_lazyDisplay))] private void InitializeDisplayAndId() { try { // AssemblyName.GetAssemblyName(path) is not available on CoreCLR. // Use our metadata reader to do the equivalent thing. using var reader = new PEReader(FileUtilities.OpenRead(FullPath)); var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); _lazyDisplay = assemblyIdentity.Name; _lazyIdentity = assemblyIdentity; } catch { _lazyDisplay = FileNameUtilities.GetFileName(FullPath, includeExtension: false); _lazyIdentity = _lazyDisplay; } } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="DiagnosticAnalyzer"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddAnalyzers(ImmutableArray<DiagnosticAnalyzer>.Builder builder, string language, Func<DiagnosticAnalyzer, bool>? shouldInclude = null) { _diagnosticAnalyzers.AddExtensions(builder, language, shouldInclude); } /// <summary> /// Adds the <see cref="ImmutableArray{T}"/> of <see cref="ISourceGenerator"/> defined in this assembly reference of given <paramref name="language"/>. /// </summary> internal void AddGenerators(ImmutableArray<ISourceGenerator>.Builder builder, string language) { _generators.AddExtensions(builder, language); } private static AnalyzerLoadFailureEventArgs CreateAnalyzerFailedArgs(Exception e, string? typeName = null) { // unwrap: e = (e as TargetInvocationException) ?? e; // remove all line breaks from the exception message string message = e.Message.Replace("\r", "").Replace("\n", ""); var errorCode = (typeName != null) ? AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer : AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer; return new AnalyzerLoadFailureEventArgs(errorCode, message, e, typeName); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap() { return _diagnosticAnalyzers.GetExtensionTypeNameMap(); } /// <summary> /// Opens the analyzer dll with the metadata reader and builds a map of language -> analyzer type names. /// </summary> /// <exception cref="BadImageFormatException">The PE image format is invalid.</exception> /// <exception cref="IOException">IO error reading the metadata.</exception> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30449")] private static ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetAnalyzerTypeNameMap(string fullPath, Type attributeType, AttributeLanguagesFunc languagesFunc) { using var assembly = AssemblyMetadata.CreateFromFile(fullPath); // This is longer than strictly necessary to avoid thrashing the GC with string allocations // in the call to GetFullyQualifiedTypeNames. Specifically, this checks for the presence of // supported languages prior to creating the type names. var typeNameMap = from module in assembly.GetModules() from typeDefHandle in module.MetadataReader.TypeDefinitions let typeDef = module.MetadataReader.GetTypeDefinition(typeDefHandle) let supportedLanguages = GetSupportedLanguages(typeDef, module.Module, attributeType, languagesFunc) where supportedLanguages.Any() let typeName = GetFullyQualifiedTypeName(typeDef, module.Module) from supportedLanguage in supportedLanguages group typeName by supportedLanguage; return typeNameMap.ToImmutableSortedDictionary(g => g.Key, g => g.ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); } private static IEnumerable<string> GetSupportedLanguages(TypeDefinition typeDef, PEModule peModule, Type attributeType, AttributeLanguagesFunc languagesFunc) { IEnumerable<string>? result = null; foreach (CustomAttributeHandle customAttrHandle in typeDef.GetCustomAttributes()) { if (peModule.IsTargetAttribute(customAttrHandle, attributeType.Namespace!, attributeType.Name, ctor: out _)) { if (languagesFunc(peModule, customAttrHandle) is { } attributeSupportedLanguages) { if (result is null) { result = attributeSupportedLanguages; } else { // This is a slow path, but only occurs if a single type has multiple // DiagnosticAnalyzerAttribute instances applied to it. result = result.Concat(attributeSupportedLanguages); } } } } return result ?? SpecializedCollections.EmptyEnumerable<string>(); } private static IEnumerable<string> GetDiagnosticsAnalyzerSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The DiagnosticAnalyzerAttribute has one constructor, which has a string parameter for the // first supported language and an array parameter for additional supported languages. // Parse the argument blob to extract the languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); return ReadLanguagesFromAttribute(ref argsReader); } private static IEnumerable<string> GetGeneratorSupportedLanguages(PEModule peModule, CustomAttributeHandle customAttrHandle) { // The GeneratorAttribute has two constructors: one default, and one with a string parameter for the // first supported language and an array parameter for additional supported languages. BlobReader argsReader = peModule.GetMemoryReaderOrThrow(peModule.GetCustomAttributeValueOrThrow(customAttrHandle)); if (argsReader.Length == 4) { // default ctor return ImmutableArray.Create(LanguageNames.CSharp); } else { // Parse the argument blob to extract the languages. return ReadLanguagesFromAttribute(ref argsReader); } } // https://github.com/dotnet/roslyn/issues/53994 tracks re-enabling nullable and fixing this method #nullable disable private static IEnumerable<string> ReadLanguagesFromAttribute(ref BlobReader argsReader) { if (argsReader.Length > 4) { // Arguments are present--check prologue. if (argsReader.ReadByte() == 1 && argsReader.ReadByte() == 0) { string firstLanguageName; if (!PEModule.CrackStringInAttributeValue(out firstLanguageName, ref argsReader)) { return SpecializedCollections.EmptyEnumerable<string>(); } ImmutableArray<string> additionalLanguageNames; if (PEModule.CrackStringArrayInAttributeValue(out additionalLanguageNames, ref argsReader)) { if (additionalLanguageNames.Length == 0) { return SpecializedCollections.SingletonEnumerable(firstLanguageName); } return additionalLanguageNames.Insert(0, firstLanguageName); } } } return SpecializedCollections.EmptyEnumerable<string>(); } #nullable enable private static ISourceGenerator? CoerceGeneratorType(object? generator) { if (generator is IIncrementalGenerator incrementalGenerator) { return new IncrementalGeneratorWrapper(incrementalGenerator); } return null; } private static string GetFullyQualifiedTypeName(TypeDefinition typeDef, PEModule peModule) { var declaringType = typeDef.GetDeclaringType(); // Non nested type - simply get the full name if (declaringType.IsNil) { return peModule.GetFullNameOrThrow(typeDef.Namespace, typeDef.Name); } else { var declaringTypeDef = peModule.MetadataReader.GetTypeDefinition(declaringType); return GetFullyQualifiedTypeName(declaringTypeDef, peModule) + "+" + peModule.MetadataReader.GetString(typeDef.Name); } } private sealed class Extensions<TExtension> where TExtension : class { private readonly AnalyzerFileReference _reference; private readonly Type _attributeType; private readonly AttributeLanguagesFunc _languagesFunc; private readonly bool _allowNetFramework; private readonly Func<object?, TExtension?>? _coerceFunction; private ImmutableArray<TExtension> _lazyAllExtensions; private ImmutableDictionary<string, ImmutableArray<TExtension>> _lazyExtensionsPerLanguage; private ImmutableSortedDictionary<string, ImmutableSortedSet<string>>? _lazyExtensionTypeNameMap; internal Extensions(AnalyzerFileReference reference, Type attributeType, AttributeLanguagesFunc languagesFunc, bool allowNetFramework, Func<object?, TExtension?>? coerceFunction = null) { _reference = reference; _attributeType = attributeType; _languagesFunc = languagesFunc; _allowNetFramework = allowNetFramework; _coerceFunction = coerceFunction; _lazyAllExtensions = default; _lazyExtensionsPerLanguage = ImmutableDictionary<string, ImmutableArray<TExtension>>.Empty; } internal ImmutableArray<TExtension> GetExtensionsForAllLanguages(bool includeDuplicates) { if (_lazyAllExtensions.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyAllExtensions, CreateExtensionsForAllLanguages(this, includeDuplicates)); } return _lazyAllExtensions; } private static ImmutableArray<TExtension> CreateExtensionsForAllLanguages(Extensions<TExtension> extensions, bool includeDuplicates) { // Get all analyzers in the assembly. var map = ImmutableSortedDictionary.CreateBuilder<string, ImmutableArray<TExtension>>(StringComparer.OrdinalIgnoreCase); extensions.AddExtensions(map); var builder = ImmutableArray.CreateBuilder<TExtension>(); foreach (var analyzers in map.Values) { foreach (var analyzer in analyzers) { builder.Add(analyzer); } } if (includeDuplicates) { return builder.ToImmutable(); } else { return builder.Distinct(ExtTypeComparer.Instance).ToImmutableArray(); } } private class ExtTypeComparer : IEqualityComparer<TExtension> { public static readonly ExtTypeComparer Instance = new(); public bool Equals(TExtension? x, TExtension? y) => object.Equals(x?.GetType(), y?.GetType()); public int GetHashCode(TExtension obj) => obj.GetType().GetHashCode(); } internal ImmutableArray<TExtension> GetExtensions(string language) { if (string.IsNullOrEmpty(language)) { throw new ArgumentException("language"); } return ImmutableInterlocked.GetOrAdd(ref _lazyExtensionsPerLanguage, language, CreateLanguageSpecificExtensions, this); } private static ImmutableArray<TExtension> CreateLanguageSpecificExtensions(string language, Extensions<TExtension> extensions) { // Get all analyzers in the assembly for the given language. var builder = ImmutableArray.CreateBuilder<TExtension>(); extensions.AddExtensions(builder, language); return builder.ToImmutable(); } internal ImmutableSortedDictionary<string, ImmutableSortedSet<string>> GetExtensionTypeNameMap() { if (_lazyExtensionTypeNameMap == null) { var analyzerTypeNameMap = GetAnalyzerTypeNameMap(_reference.FullPath, _attributeType, _languagesFunc); Interlocked.CompareExchange(ref _lazyExtensionTypeNameMap, analyzerTypeNameMap, null); } return _lazyExtensionTypeNameMap; } internal void AddExtensions(ImmutableSortedDictionary<string, ImmutableArray<TExtension>>.Builder builder) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); if (analyzerTypeNameMap.Count == 0) { return; } analyzerAssembly = _reference.GetAssembly(); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var initialCount = builder.Count; var reportedError = false; // Add language specific analyzers. foreach (var (language, _) in analyzerTypeNameMap) { if (language == null) { continue; } var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); builder.Add(language, analyzers); } // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (builder.Count == initialCount && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } internal void AddExtensions(ImmutableArray<TExtension>.Builder builder, string language, Func<TExtension, bool>? shouldInclude = null) { ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap; Assembly analyzerAssembly; try { analyzerTypeNameMap = GetExtensionTypeNameMap(); // If there are no analyzers, don't load the assembly at all. if (!analyzerTypeNameMap.ContainsKey(language)) { return; } analyzerAssembly = _reference.GetAssembly(); if (analyzerAssembly == null) { // This can be null if NoOpAnalyzerAssemblyLoader is used. return; } } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e)); return; } var reportedError = false; // Add language specific analyzers. var analyzers = GetLanguageSpecificAnalyzers(analyzerAssembly, analyzerTypeNameMap, language, ref reportedError); var hasAnalyzers = !analyzers.IsEmpty; if (shouldInclude != null) { analyzers = analyzers.WhereAsArray(shouldInclude); } builder.AddRange(analyzers); // If there were types with the attribute but weren't an analyzer, generate a diagnostic. // If we've reported errors already while trying to instantiate types, don't complain that there are no analyzers. if (!hasAnalyzers && !reportedError) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs(AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers, CodeAnalysisResources.NoAnalyzersFound)); } } private ImmutableArray<TExtension> GetLanguageSpecificAnalyzers(Assembly analyzerAssembly, ImmutableSortedDictionary<string, ImmutableSortedSet<string>> analyzerTypeNameMap, string language, ref bool reportedError) { ImmutableSortedSet<string>? languageSpecificAnalyzerTypeNames; if (!analyzerTypeNameMap.TryGetValue(language, out languageSpecificAnalyzerTypeNames)) { return ImmutableArray<TExtension>.Empty; } return this.GetAnalyzersForTypeNames(analyzerAssembly, languageSpecificAnalyzerTypeNames, ref reportedError); } private ImmutableArray<TExtension> GetAnalyzersForTypeNames(Assembly analyzerAssembly, IEnumerable<string> analyzerTypeNames, ref bool reportedError) { var analyzers = ImmutableArray.CreateBuilder<TExtension>(); // Given the type names, get the actual System.Type and try to create an instance of the type through reflection. foreach (var typeName in analyzerTypeNames) { Type? type; try { type = analyzerAssembly.GetType(typeName, throwOnError: true, ignoreCase: false); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } Debug.Assert(type != null); // check if this references net framework, and issue a diagnostic that this isn't supported if (!_allowNetFramework) { var targetFrameworkAttribute = analyzerAssembly.GetCustomAttribute<TargetFrameworkAttribute>(); if (targetFrameworkAttribute is object && targetFrameworkAttribute.FrameworkName.StartsWith(".NETFramework", StringComparison.OrdinalIgnoreCase)) { _reference.AnalyzerLoadFailed?.Invoke(_reference, new AnalyzerLoadFailureEventArgs( AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework, string.Format(CodeAnalysisResources.AssemblyReferencesNetFramework, typeName), typeNameOpt: typeName)); continue; } } object? typeInstance; try { typeInstance = Activator.CreateInstance(type); } catch (Exception e) { _reference.AnalyzerLoadFailed?.Invoke(_reference, CreateAnalyzerFailedArgs(e, typeName)); reportedError = true; continue; } TExtension? analyzer = typeInstance as TExtension ?? _coerceFunction?.Invoke(typeInstance); if (analyzer != null) { analyzers.Add(analyzer); } } return analyzers.ToImmutable(); } } public Assembly GetAssembly() { if (_lazyAssembly == null) { _lazyAssembly = _assemblyLoader.LoadFromPath(FullPath); } return _lazyAssembly; } } }
1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/Core/Def/Implementation/LanguageClient/VisualStudioInProcLanguageServer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using StreamJsonRpc; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Implementation of <see cref="LanguageServerTarget"/> that also supports /// VS LSP extension methods. /// </summary> internal class VisualStudioInProcLanguageServer : LanguageServerTarget { /// <summary> /// Legacy support for LSP push diagnostics. /// Work queue responsible for receiving notifications about diagnostic updates and publishing those to /// interested parties. /// </summary> private readonly AsyncBatchingWorkQueue<DocumentId> _diagnosticsWorkQueue; private readonly IDiagnosticService? _diagnosticService; internal VisualStudioInProcLanguageServer( AbstractRequestDispatcherFactory requestDispatcherFactory, JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider, ILspLogger logger, IDiagnosticService? diagnosticService, ImmutableArray<string> supportedLanguages, string? clientName, string userVisibleServerName, string telemetryServerTypeName) : base(requestDispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, globalOptions, listenerProvider, logger, supportedLanguages, clientName, userVisibleServerName, telemetryServerTypeName) { _diagnosticService = diagnosticService; // Dedupe on DocumentId. If we hear about the same document multiple times, we only need to process that id once. _diagnosticsWorkQueue = new AsyncBatchingWorkQueue<DocumentId>( TimeSpan.FromMilliseconds(250), (ids, ct) => ProcessDiagnosticUpdatedBatchAsync(_diagnosticService, ids, ct), EqualityComparer<DocumentId>.Default, Listener, Queue.CancellationToken); if (_diagnosticService != null) _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated; } public override Task InitializedAsync() { try { Logger?.TraceStart("Initialized"); // Publish diagnostics for all open documents immediately following initialization. PublishOpenFileDiagnostics(); return Task.CompletedTask; } finally { Logger?.TraceStop("Initialized"); } void PublishOpenFileDiagnostics() { foreach (var workspace in WorkspaceRegistrationService.GetAllRegistrations()) { var solution = workspace.CurrentSolution; var openDocuments = workspace.GetOpenDocumentIds(); foreach (var documentId in openDocuments) DiagnosticService_DiagnosticsUpdated(solution, documentId); } } } [JsonRpcMethod(VSInternalMethods.DocumentPullDiagnosticName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalDiagnosticReport[]?> GetDocumentPullDiagnosticsAsync(VSInternalDocumentDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentDiagnosticsParams, VSInternalDiagnosticReport[]?>( Queue, VSInternalMethods.DocumentPullDiagnosticName, diagnosticsParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSInternalMethods.WorkspacePullDiagnosticName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalWorkspaceDiagnosticReport[]?> GetWorkspacePullDiagnosticsAsync(VSInternalWorkspaceDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport[]?>( Queue, VSInternalMethods.WorkspacePullDiagnosticName, diagnosticsParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSMethods.GetProjectContextsName, UseSingleObjectParameterDeserialization = true)] public Task<VSProjectContextList?> GetProjectContextsAsync(VSGetProjectContextsParams textDocumentWithContextParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSGetProjectContextsParams, VSProjectContextList?>(Queue, VSMethods.GetProjectContextsName, textDocumentWithContextParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSInternalMethods.OnAutoInsertName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalDocumentOnAutoInsertResponseItem?> GetDocumentOnAutoInsertAsync(VSInternalDocumentOnAutoInsertParams autoInsertParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentOnAutoInsertParams, VSInternalDocumentOnAutoInsertResponseItem?>(Queue, VSInternalMethods.OnAutoInsertName, autoInsertParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(Methods.TextDocumentLinkedEditingRangeName, UseSingleObjectParameterDeserialization = true)] public Task<LinkedEditingRanges?> GetLinkedEditingRangesAsync(LinkedEditingRangeParams renameParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<LinkedEditingRangeParams, LinkedEditingRanges?>(Queue, Methods.TextDocumentLinkedEditingRangeName, renameParams, _clientCapabilities, ClientName, cancellationToken); } protected override void ShutdownImpl() { base.ShutdownImpl(); if (_diagnosticService != null) _diagnosticService.DiagnosticsUpdated -= DiagnosticService_DiagnosticsUpdated; } private void DiagnosticService_DiagnosticsUpdated(object _, DiagnosticsUpdatedArgs e) => DiagnosticService_DiagnosticsUpdated(e.Solution, e.DocumentId); private void DiagnosticService_DiagnosticsUpdated(Solution? solution, DocumentId? documentId) { // LSP doesn't support diagnostics without a document. So if we get project level diagnostics without a document, ignore them. if (documentId != null && solution != null) { var document = solution.GetDocument(documentId); if (document == null || document.FilePath == null) return; // Only publish document diagnostics for the languages this provider supports. if (document.Project.Language is not CodeAnalysis.LanguageNames.CSharp and not CodeAnalysis.LanguageNames.VisualBasic) return; _diagnosticsWorkQueue.AddWork(document.Id); } } /// <summary> /// Stores the last published LSP diagnostics with the Roslyn document that they came from. /// This is useful in the following scenario. Imagine we have documentA which has contributions to mapped files m1 and m2. /// dA -> m1 /// And m1 has contributions from documentB. /// m1 -> dA, dB /// When we query for diagnostic on dA, we get a subset of the diagnostics on m1 (missing the contributions from dB) /// Since each publish diagnostics notification replaces diagnostics per document, /// we must union the diagnostics contribution from dB and dA to produce all diagnostics for m1 and publish all at once. /// /// This dictionary stores the previously computed diagnostics for the published file so that we can /// union the currently computed diagnostics (e.g. for dA) with previously computed diagnostics (e.g. from dB). /// </summary> private readonly Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LSP.Diagnostic>>> _publishedFileToDiagnostics = new(); /// <summary> /// Stores the mapping of a document to the uri(s) of diagnostics previously produced for this document. When /// we get empty diagnostics for the document we need to find the uris we previously published for this /// document. Then we can publish the updated diagnostics set for those uris (either empty or the diagnostic /// contributions from other documents). We use a sorted set to ensure consistency in the order in which we /// report URIs. While it's not necessary to publish a document's mapped file diagnostics in a particular /// order, it does make it much easier to write tests and debug issues if we have a consistent ordering. /// </summary> private readonly Dictionary<DocumentId, ImmutableSortedSet<Uri>> _documentsToPublishedUris = new(); /// <summary> /// Basic comparer for Uris used by <see cref="_documentsToPublishedUris"/> when publishing notifications. /// </summary> private static readonly Comparer<Uri> s_uriComparer = Comparer<Uri>.Create((uri1, uri2) => Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // internal for testing purposes internal async ValueTask ProcessDiagnosticUpdatedBatchAsync( IDiagnosticService? diagnosticService, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (diagnosticService == null) return; foreach (var documentId in documentIds) { cancellationToken.ThrowIfCancellationRequested(); var document = WorkspaceRegistrationService.GetAllRegistrations().Select(w => w.CurrentSolution.GetDocument(documentId)).FirstOrDefault(); if (document != null) { // If this is a `pull` client, and `pull` diagnostics is on, then we should not `publish` (push) the // diagnostics here. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; if (GlobalOptions.IsPushDiagnostics(diagnosticMode)) await PublishDiagnosticsAsync(diagnosticService, document, cancellationToken).ConfigureAwait(false); } } } private async Task PublishDiagnosticsAsync(IDiagnosticService diagnosticService, Document document, CancellationToken cancellationToken) { // Retrieve all diagnostics for the current document grouped by their actual file uri. var fileUriToDiagnostics = await GetDiagnosticsAsync(diagnosticService, document, cancellationToken).ConfigureAwait(false); // Get the list of file uris with diagnostics (for the document). // We need to join the uris from current diagnostics with those previously published // so that we clear out any diagnostics in mapped files that are no longer a part // of the current diagnostics set (because the diagnostics were fixed). // Use sorted set to have consistent publish ordering for tests and debugging. var urisForCurrentDocument = _documentsToPublishedUris.GetValueOrDefault(document.Id, ImmutableSortedSet.Create<Uri>(s_uriComparer)).Union(fileUriToDiagnostics.Keys); // Update the mapping for this document to be the uris we're about to publish diagnostics for. _documentsToPublishedUris[document.Id] = urisForCurrentDocument; // Go through each uri and publish the updated set of diagnostics per uri. foreach (var fileUri in urisForCurrentDocument) { // Get the updated diagnostics for a single uri that were contributed by the current document. var diagnostics = fileUriToDiagnostics.GetValueOrDefault(fileUri, ImmutableArray<LSP.Diagnostic>.Empty); if (_publishedFileToDiagnostics.ContainsKey(fileUri)) { // Get all previously published diagnostics for this uri excluding those that were contributed from the current document. // We don't need those since we just computed the updated values above. var diagnosticsFromOtherDocuments = _publishedFileToDiagnostics[fileUri].Where(kvp => kvp.Key != document.Id).SelectMany(kvp => kvp.Value); // Since diagnostics are replaced per uri, we must publish both contributions from this document and any other document // that has diagnostic contributions to this uri, so union the two sets. diagnostics = diagnostics.AddRange(diagnosticsFromOtherDocuments); } await SendDiagnosticsNotificationAsync(fileUri, diagnostics).ConfigureAwait(false); // There are three cases here -> // 1. There are no diagnostics to publish for this fileUri. We no longer need to track the fileUri at all. // 2. There are diagnostics from the current document. Store the diagnostics for the fileUri and document // so they can be published along with contributions to the fileUri from other documents. // 3. There are no diagnostics contributed by this document to the fileUri (could be some from other documents). // We should clear out the diagnostics for this document for the fileUri. if (diagnostics.IsEmpty) { // We published an empty set of diagnostics for this uri. We no longer need to keep track of this mapping // since there will be no previous diagnostics that we need to clear out. _documentsToPublishedUris.MultiRemove(document.Id, fileUri); // There are not any diagnostics to keep track of for this file, so we can stop. _publishedFileToDiagnostics.Remove(fileUri); } else if (fileUriToDiagnostics.ContainsKey(fileUri)) { // We do have diagnostics from the current document - update the published diagnostics map // to contain the new diagnostics contributed by this document for this uri. var documentsToPublishedDiagnostics = _publishedFileToDiagnostics.GetOrAdd(fileUri, (_) => new Dictionary<DocumentId, ImmutableArray<LSP.Diagnostic>>()); documentsToPublishedDiagnostics[document.Id] = fileUriToDiagnostics[fileUri]; } else { // There were diagnostics from other documents, but none from the current document. // If we're tracking the current document, we can stop. IReadOnlyDictionaryExtensions.GetValueOrDefault(_publishedFileToDiagnostics, fileUri)?.Remove(document.Id); _documentsToPublishedUris.MultiRemove(document.Id, fileUri); } } } private async Task SendDiagnosticsNotificationAsync(Uri uri, ImmutableArray<LSP.Diagnostic> diagnostics) { var publishDiagnosticsParams = new PublishDiagnosticParams { Diagnostics = diagnostics.ToArray(), Uri = uri }; await JsonRpc.NotifyWithParameterObjectAsync(Methods.TextDocumentPublishDiagnosticsName, publishDiagnosticsParams).ConfigureAwait(false); } private async Task<Dictionary<Uri, ImmutableArray<LSP.Diagnostic>>> GetDiagnosticsAsync( IDiagnosticService diagnosticService, Document document, CancellationToken cancellationToken) { var option = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var pushDiagnostics = await diagnosticService.GetPushDiagnosticsAsync(document.Project.Solution.Workspace, document.Project.Id, document.Id, id: null, includeSuppressedDiagnostics: false, option, cancellationToken).ConfigureAwait(false); var diagnostics = pushDiagnostics.WhereAsArray(IncludeDiagnostic); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // Retrieve diagnostics for the document. These diagnostics could be for the current document, or they could map // to a different location in a different file. We need to publish the diagnostics for the mapped locations as well. // An example of this is razor imports where the generated C# document maps to many razor documents. // https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-3.1#importing-shared-directives // https://docs.microsoft.com/en-us/aspnet/core/blazor/layouts?view=aspnetcore-3.1#centralized-layout-selection // So we get the diagnostics and group them by the actual mapped path so we can publish notifications // for each mapped file's diagnostics. var fileUriToDiagnostics = diagnostics.GroupBy(diagnostic => GetDiagnosticUri(document, diagnostic)).ToDictionary( group => group.Key, group => group.Select(diagnostic => ConvertToLspDiagnostic(diagnostic, text)).ToImmutableArray()); return fileUriToDiagnostics; static Uri GetDiagnosticUri(Document document, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.DataLocation, "Diagnostic data location should not be null here"); // Razor wants to handle all span mapping themselves. So if we are in razor, return the raw doc spans, and // do not map them. var filePath = diagnosticData.DataLocation.MappedFilePath ?? diagnosticData.DataLocation.OriginalFilePath; return ProtocolConversions.GetUriFromFilePath(filePath); } } private LSP.Diagnostic ConvertToLspDiagnostic(DiagnosticData diagnosticData, SourceText text) { Contract.ThrowIfNull(diagnosticData.DataLocation); var diagnostic = new LSP.Diagnostic { Source = TelemetryServerName, Code = diagnosticData.Id, Severity = Convert(diagnosticData.Severity), Range = GetDiagnosticRange(diagnosticData.DataLocation, text), // Only the unnecessary diagnostic tag is currently supported via LSP. Tags = diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary) ? new DiagnosticTag[] { DiagnosticTag.Unnecessary } : Array.Empty<DiagnosticTag>() }; if (diagnosticData.Message != null) diagnostic.Message = diagnosticData.Message; return diagnostic; } private static LSP.DiagnosticSeverity Convert(CodeAnalysis.DiagnosticSeverity severity) => severity switch { CodeAnalysis.DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, CodeAnalysis.DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, CodeAnalysis.DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, CodeAnalysis.DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; // Some diagnostics only apply to certain clients and document types, e.g. Razor. // If the DocumentPropertiesService.DiagnosticsLspClientName property exists, we only include the // diagnostic if it directly matches the client name. // If the DocumentPropertiesService.DiagnosticsLspClientName property doesn't exist, // we know that the diagnostic we're working with is contained in a C#/VB file, since // if we were working with a non-C#/VB file, then the property should have been populated. // In this case, unless we have a null client name, we don't want to publish the diagnostic // (since a null client name represents the C#/VB language server). private bool IncludeDiagnostic(DiagnosticData diagnostic) => IReadOnlyDictionaryExtensions.GetValueOrDefault(diagnostic.Properties, nameof(DocumentPropertiesService.DiagnosticsLspClientName)) == ClientName; private static LSP.Range GetDiagnosticRange(DiagnosticDataLocation diagnosticDataLocation, SourceText text) { var linePositionSpan = DiagnosticData.GetLinePositionSpan(diagnosticDataLocation, text, useMapped: true); return ProtocolConversions.LinePositionToRange(linePositionSpan); } internal new TestAccessor GetTestAccessor() => new(this); internal new readonly struct TestAccessor { private readonly VisualStudioInProcLanguageServer _server; internal TestAccessor(VisualStudioInProcLanguageServer server) { _server = server; } internal ImmutableArray<Uri> GetFileUrisInPublishDiagnostics() => _server._publishedFileToDiagnostics.Keys.ToImmutableArray(); internal ImmutableArray<DocumentId> GetDocumentIdsInPublishedUris() => _server._documentsToPublishedUris.Keys.ToImmutableArray(); internal IImmutableSet<Uri> GetFileUrisForDocument(DocumentId documentId) => _server._documentsToPublishedUris.GetValueOrDefault(documentId, ImmutableSortedSet<Uri>.Empty); internal ImmutableArray<LSP.Diagnostic> GetDiagnosticsForUriAndDocument(DocumentId documentId, Uri uri) { if (_server._publishedFileToDiagnostics.TryGetValue(uri, out var dict) && dict.TryGetValue(documentId, out var diagnostics)) return diagnostics; return ImmutableArray<LSP.Diagnostic>.Empty; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.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.Host; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using StreamJsonRpc; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { /// <summary> /// Implementation of <see cref="LanguageServerTarget"/> that also supports /// VS LSP extension methods. /// </summary> internal class VisualStudioInProcLanguageServer : LanguageServerTarget { /// <summary> /// Legacy support for LSP push diagnostics. /// Work queue responsible for receiving notifications about diagnostic updates and publishing those to /// interested parties. /// </summary> private readonly AsyncBatchingWorkQueue<DocumentId> _diagnosticsWorkQueue; private readonly IDiagnosticService? _diagnosticService; internal VisualStudioInProcLanguageServer( AbstractRequestDispatcherFactory requestDispatcherFactory, JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, IGlobalOptionService globalOptions, IAsynchronousOperationListenerProvider listenerProvider, ILspLogger logger, IDiagnosticService? diagnosticService, ImmutableArray<string> supportedLanguages, string? clientName, string userVisibleServerName, string telemetryServerTypeName) : base(requestDispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, globalOptions, listenerProvider, logger, supportedLanguages, clientName, userVisibleServerName, telemetryServerTypeName) { _diagnosticService = diagnosticService; // Dedupe on DocumentId. If we hear about the same document multiple times, we only need to process that id once. _diagnosticsWorkQueue = new AsyncBatchingWorkQueue<DocumentId>( TimeSpan.FromMilliseconds(250), (ids, ct) => ProcessDiagnosticUpdatedBatchAsync(_diagnosticService, ids, ct), EqualityComparer<DocumentId>.Default, Listener, Queue.CancellationToken); if (_diagnosticService != null) _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated; } public override Task InitializedAsync() { try { Logger?.TraceStart("Initialized"); // Publish diagnostics for all open documents immediately following initialization. PublishOpenFileDiagnostics(); return Task.CompletedTask; } finally { Logger?.TraceStop("Initialized"); } void PublishOpenFileDiagnostics() { foreach (var workspace in WorkspaceRegistrationService.GetAllRegistrations()) { var solution = workspace.CurrentSolution; var openDocuments = workspace.GetOpenDocumentIds(); foreach (var documentId in openDocuments) DiagnosticService_DiagnosticsUpdated(solution, documentId); } } } [JsonRpcMethod(VSInternalMethods.DocumentPullDiagnosticName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalDiagnosticReport[]?> GetDocumentPullDiagnosticsAsync(VSInternalDocumentDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentDiagnosticsParams, VSInternalDiagnosticReport[]?>( Queue, VSInternalMethods.DocumentPullDiagnosticName, diagnosticsParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSInternalMethods.WorkspacePullDiagnosticName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalWorkspaceDiagnosticReport[]?> GetWorkspacePullDiagnosticsAsync(VSInternalWorkspaceDiagnosticsParams diagnosticsParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalWorkspaceDiagnosticsParams, VSInternalWorkspaceDiagnosticReport[]?>( Queue, VSInternalMethods.WorkspacePullDiagnosticName, diagnosticsParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSMethods.GetProjectContextsName, UseSingleObjectParameterDeserialization = true)] public Task<VSProjectContextList?> GetProjectContextsAsync(VSGetProjectContextsParams textDocumentWithContextParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSGetProjectContextsParams, VSProjectContextList?>(Queue, VSMethods.GetProjectContextsName, textDocumentWithContextParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(VSInternalMethods.OnAutoInsertName, UseSingleObjectParameterDeserialization = true)] public Task<VSInternalDocumentOnAutoInsertResponseItem?> GetDocumentOnAutoInsertAsync(VSInternalDocumentOnAutoInsertParams autoInsertParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<VSInternalDocumentOnAutoInsertParams, VSInternalDocumentOnAutoInsertResponseItem?>(Queue, VSInternalMethods.OnAutoInsertName, autoInsertParams, _clientCapabilities, ClientName, cancellationToken); } [JsonRpcMethod(Methods.TextDocumentLinkedEditingRangeName, UseSingleObjectParameterDeserialization = true)] public Task<LinkedEditingRanges?> GetLinkedEditingRangesAsync(LinkedEditingRangeParams renameParams, CancellationToken cancellationToken) { Contract.ThrowIfNull(_clientCapabilities, $"{nameof(InitializeAsync)} has not been called."); return RequestDispatcher.ExecuteRequestAsync<LinkedEditingRangeParams, LinkedEditingRanges?>(Queue, Methods.TextDocumentLinkedEditingRangeName, renameParams, _clientCapabilities, ClientName, cancellationToken); } protected override void ShutdownImpl() { base.ShutdownImpl(); if (_diagnosticService != null) _diagnosticService.DiagnosticsUpdated -= DiagnosticService_DiagnosticsUpdated; } private void DiagnosticService_DiagnosticsUpdated(object _, DiagnosticsUpdatedArgs e) => DiagnosticService_DiagnosticsUpdated(e.Solution, e.DocumentId); private void DiagnosticService_DiagnosticsUpdated(Solution? solution, DocumentId? documentId) { // LSP doesn't support diagnostics without a document. So if we get project level diagnostics without a document, ignore them. if (documentId != null && solution != null) { var document = solution.GetDocument(documentId); if (document == null || document.FilePath == null) return; // Only publish document diagnostics for the languages this provider supports. if (document.Project.Language is not CodeAnalysis.LanguageNames.CSharp and not CodeAnalysis.LanguageNames.VisualBasic) return; _diagnosticsWorkQueue.AddWork(document.Id); } } /// <summary> /// Stores the last published LSP diagnostics with the Roslyn document that they came from. /// This is useful in the following scenario. Imagine we have documentA which has contributions to mapped files m1 and m2. /// dA -> m1 /// And m1 has contributions from documentB. /// m1 -> dA, dB /// When we query for diagnostic on dA, we get a subset of the diagnostics on m1 (missing the contributions from dB) /// Since each publish diagnostics notification replaces diagnostics per document, /// we must union the diagnostics contribution from dB and dA to produce all diagnostics for m1 and publish all at once. /// /// This dictionary stores the previously computed diagnostics for the published file so that we can /// union the currently computed diagnostics (e.g. for dA) with previously computed diagnostics (e.g. from dB). /// </summary> private readonly Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LSP.Diagnostic>>> _publishedFileToDiagnostics = new(); /// <summary> /// Stores the mapping of a document to the uri(s) of diagnostics previously produced for this document. When /// we get empty diagnostics for the document we need to find the uris we previously published for this /// document. Then we can publish the updated diagnostics set for those uris (either empty or the diagnostic /// contributions from other documents). We use a sorted set to ensure consistency in the order in which we /// report URIs. While it's not necessary to publish a document's mapped file diagnostics in a particular /// order, it does make it much easier to write tests and debug issues if we have a consistent ordering. /// </summary> private readonly Dictionary<DocumentId, ImmutableSortedSet<Uri>> _documentsToPublishedUris = new(); /// <summary> /// Basic comparer for Uris used by <see cref="_documentsToPublishedUris"/> when publishing notifications. /// </summary> private static readonly Comparer<Uri> s_uriComparer = Comparer<Uri>.Create((uri1, uri2) => Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase)); // internal for testing purposes internal async ValueTask ProcessDiagnosticUpdatedBatchAsync( IDiagnosticService? diagnosticService, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (diagnosticService == null) return; foreach (var documentId in documentIds) { cancellationToken.ThrowIfCancellationRequested(); var document = WorkspaceRegistrationService.GetAllRegistrations().Select(w => w.CurrentSolution.GetDocument(documentId)).FirstOrDefault(); if (document != null) { // If this is a `pull` client, and `pull` diagnostics is on, then we should not `publish` (push) the // diagnostics here. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; if (GlobalOptions.IsPushDiagnostics(diagnosticMode)) await PublishDiagnosticsAsync(diagnosticService, document, cancellationToken).ConfigureAwait(false); } } } private async Task PublishDiagnosticsAsync(IDiagnosticService diagnosticService, Document document, CancellationToken cancellationToken) { // Retrieve all diagnostics for the current document grouped by their actual file uri. var fileUriToDiagnostics = await GetDiagnosticsAsync(diagnosticService, document, cancellationToken).ConfigureAwait(false); // Get the list of file uris with diagnostics (for the document). // We need to join the uris from current diagnostics with those previously published // so that we clear out any diagnostics in mapped files that are no longer a part // of the current diagnostics set (because the diagnostics were fixed). // Use sorted set to have consistent publish ordering for tests and debugging. var urisForCurrentDocument = _documentsToPublishedUris.GetValueOrDefault(document.Id, ImmutableSortedSet.Create<Uri>(s_uriComparer)).Union(fileUriToDiagnostics.Keys); // Update the mapping for this document to be the uris we're about to publish diagnostics for. _documentsToPublishedUris[document.Id] = urisForCurrentDocument; // Go through each uri and publish the updated set of diagnostics per uri. foreach (var fileUri in urisForCurrentDocument) { // Get the updated diagnostics for a single uri that were contributed by the current document. var diagnostics = fileUriToDiagnostics.GetValueOrDefault(fileUri, ImmutableArray<LSP.Diagnostic>.Empty); if (_publishedFileToDiagnostics.ContainsKey(fileUri)) { // Get all previously published diagnostics for this uri excluding those that were contributed from the current document. // We don't need those since we just computed the updated values above. var diagnosticsFromOtherDocuments = _publishedFileToDiagnostics[fileUri].Where(kvp => kvp.Key != document.Id).SelectMany(kvp => kvp.Value); // Since diagnostics are replaced per uri, we must publish both contributions from this document and any other document // that has diagnostic contributions to this uri, so union the two sets. diagnostics = diagnostics.AddRange(diagnosticsFromOtherDocuments); } await SendDiagnosticsNotificationAsync(fileUri, diagnostics).ConfigureAwait(false); // There are three cases here -> // 1. There are no diagnostics to publish for this fileUri. We no longer need to track the fileUri at all. // 2. There are diagnostics from the current document. Store the diagnostics for the fileUri and document // so they can be published along with contributions to the fileUri from other documents. // 3. There are no diagnostics contributed by this document to the fileUri (could be some from other documents). // We should clear out the diagnostics for this document for the fileUri. if (diagnostics.IsEmpty) { // We published an empty set of diagnostics for this uri. We no longer need to keep track of this mapping // since there will be no previous diagnostics that we need to clear out. _documentsToPublishedUris.MultiRemove(document.Id, fileUri); // There are not any diagnostics to keep track of for this file, so we can stop. _publishedFileToDiagnostics.Remove(fileUri); } else if (fileUriToDiagnostics.ContainsKey(fileUri)) { // We do have diagnostics from the current document - update the published diagnostics map // to contain the new diagnostics contributed by this document for this uri. var documentsToPublishedDiagnostics = _publishedFileToDiagnostics.GetOrAdd(fileUri, (_) => new Dictionary<DocumentId, ImmutableArray<LSP.Diagnostic>>()); documentsToPublishedDiagnostics[document.Id] = fileUriToDiagnostics[fileUri]; } else { // There were diagnostics from other documents, but none from the current document. // If we're tracking the current document, we can stop. IReadOnlyDictionaryExtensions.GetValueOrDefault(_publishedFileToDiagnostics, fileUri)?.Remove(document.Id); _documentsToPublishedUris.MultiRemove(document.Id, fileUri); } } } private async Task SendDiagnosticsNotificationAsync(Uri uri, ImmutableArray<LSP.Diagnostic> diagnostics) { var publishDiagnosticsParams = new PublishDiagnosticParams { Diagnostics = diagnostics.ToArray(), Uri = uri }; await JsonRpc.NotifyWithParameterObjectAsync(Methods.TextDocumentPublishDiagnosticsName, publishDiagnosticsParams).ConfigureAwait(false); } private async Task<Dictionary<Uri, ImmutableArray<LSP.Diagnostic>>> GetDiagnosticsAsync( IDiagnosticService diagnosticService, Document document, CancellationToken cancellationToken) { var option = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var pushDiagnostics = await diagnosticService.GetPushDiagnosticsAsync(document.Project.Solution.Workspace, document.Project.Id, document.Id, id: null, includeSuppressedDiagnostics: false, option, cancellationToken).ConfigureAwait(false); var diagnostics = pushDiagnostics.WhereAsArray(IncludeDiagnostic); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // Retrieve diagnostics for the document. These diagnostics could be for the current document, or they could map // to a different location in a different file. We need to publish the diagnostics for the mapped locations as well. // An example of this is razor imports where the generated C# document maps to many razor documents. // https://docs.microsoft.com/en-us/aspnet/core/mvc/views/layout?view=aspnetcore-3.1#importing-shared-directives // https://docs.microsoft.com/en-us/aspnet/core/blazor/layouts?view=aspnetcore-3.1#centralized-layout-selection // So we get the diagnostics and group them by the actual mapped path so we can publish notifications // for each mapped file's diagnostics. var fileUriToDiagnostics = diagnostics.GroupBy(diagnostic => GetDiagnosticUri(document, diagnostic)).ToDictionary( group => group.Key, group => group.Select(diagnostic => ConvertToLspDiagnostic(diagnostic, text)).ToImmutableArray()); return fileUriToDiagnostics; static Uri GetDiagnosticUri(Document document, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.DataLocation, "Diagnostic data location should not be null here"); // Razor wants to handle all span mapping themselves. So if we are in razor, return the raw doc spans, and // do not map them. var filePath = diagnosticData.DataLocation.MappedFilePath ?? diagnosticData.DataLocation.OriginalFilePath; return ProtocolConversions.GetUriFromFilePath(filePath); } } private LSP.Diagnostic ConvertToLspDiagnostic(DiagnosticData diagnosticData, SourceText text) { Contract.ThrowIfNull(diagnosticData.DataLocation); var diagnostic = new LSP.Diagnostic { Source = TelemetryServerName, Code = diagnosticData.Id, Severity = Convert(diagnosticData.Severity), Range = GetDiagnosticRange(diagnosticData.DataLocation, text), // Only the unnecessary diagnostic tag is currently supported via LSP. Tags = diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary) ? new DiagnosticTag[] { DiagnosticTag.Unnecessary } : Array.Empty<DiagnosticTag>() }; if (diagnosticData.Message != null) diagnostic.Message = diagnosticData.Message; return diagnostic; } private static LSP.DiagnosticSeverity Convert(CodeAnalysis.DiagnosticSeverity severity) => severity switch { CodeAnalysis.DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, CodeAnalysis.DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, CodeAnalysis.DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, CodeAnalysis.DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; // Some diagnostics only apply to certain clients and document types, e.g. Razor. // If the DocumentPropertiesService.DiagnosticsLspClientName property exists, we only include the // diagnostic if it directly matches the client name. // If the DocumentPropertiesService.DiagnosticsLspClientName property doesn't exist, // we know that the diagnostic we're working with is contained in a C#/VB file, since // if we were working with a non-C#/VB file, then the property should have been populated. // In this case, unless we have a null client name, we don't want to publish the diagnostic // (since a null client name represents the C#/VB language server). private bool IncludeDiagnostic(DiagnosticData diagnostic) => IReadOnlyDictionaryExtensions.GetValueOrDefault(diagnostic.Properties, nameof(DocumentPropertiesService.DiagnosticsLspClientName)) == ClientName; private static LSP.Range GetDiagnosticRange(DiagnosticDataLocation diagnosticDataLocation, SourceText text) { var linePositionSpan = DiagnosticData.GetLinePositionSpan(diagnosticDataLocation, text, useMapped: true); return ProtocolConversions.LinePositionToRange(linePositionSpan); } internal new TestAccessor GetTestAccessor() => new(this); internal new readonly struct TestAccessor { private readonly VisualStudioInProcLanguageServer _server; internal TestAccessor(VisualStudioInProcLanguageServer server) { _server = server; } internal ImmutableArray<Uri> GetFileUrisInPublishDiagnostics() => _server._publishedFileToDiagnostics.Keys.ToImmutableArray(); internal ImmutableArray<DocumentId> GetDocumentIdsInPublishedUris() => _server._documentsToPublishedUris.Keys.ToImmutableArray(); internal IImmutableSet<Uri> GetFileUrisForDocument(DocumentId documentId) => _server._documentsToPublishedUris.GetValueOrDefault(documentId, ImmutableSortedSet<Uri>.Empty); internal ImmutableArray<LSP.Diagnostic> GetDiagnosticsForUriAndDocument(DocumentId documentId, Uri uri) { if (_server._publishedFileToDiagnostics.TryGetValue(uri, out var dict) && dict.TryGetValue(documentId, out var diagnostics)) return diagnostics; return ImmutableArray<LSP.Diagnostic>.Empty; } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/EditorFeatures/TestUtilities/Threading/WpfTestCaseRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { public sealed class WpfTestCaseRunner : XunitTestCaseRunner { public WpfTestSharedData SharedData { get; } public WpfTestCaseRunner( WpfTestSharedData sharedData, IXunitTestCase testCase, string displayName, string skipReason, object[] constructorArguments, object[] testMethodArguments, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(testCase, displayName, skipReason, constructorArguments, testMethodArguments, messageBus, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var runner = new WpfTestRunner(SharedData, test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource); return runner; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { public sealed class WpfTestCaseRunner : XunitTestCaseRunner { public WpfTestSharedData SharedData { get; } public WpfTestCaseRunner( WpfTestSharedData sharedData, IXunitTestCase testCase, string displayName, string skipReason, object[] constructorArguments, object[] testMethodArguments, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(testCase, displayName, skipReason, constructorArguments, testMethodArguments, messageBus, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var runner = new WpfTestRunner(SharedData, test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource); return runner; } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/LiveShare/Impl/Client/Razor/CSharpLspRazorProjectFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Razor { [Export] internal class CSharpLspRazorProjectFactory { private readonly RemoteLanguageServiceWorkspaceHost _remoteLanguageServiceWorkspaceHost; private readonly Dictionary<string, ProjectId> _projects = new Dictionary<string, ProjectId>(); public ProjectId GetProject(string projectName) { if (_projects.TryGetValue(projectName, out var projectId)) { return projectId; } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectName), VersionStamp.Default, projectName, projectName, LanguageNames.CSharp); _remoteLanguageServiceWorkspaceHost.Workspace.OnProjectAdded(projectInfo); _projects.Add(projectName, projectInfo.Id); return projectInfo.Id; } public CodeAnalysis.Workspace Workspace => _remoteLanguageServiceWorkspaceHost.Workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspRazorProjectFactory(RemoteLanguageServiceWorkspaceHost remoteLanguageServiceWorkspaceHost) => _remoteLanguageServiceWorkspaceHost = remoteLanguageServiceWorkspaceHost ?? throw new ArgumentNullException(nameof(remoteLanguageServiceWorkspaceHost)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Razor { [Export] internal class CSharpLspRazorProjectFactory { private readonly RemoteLanguageServiceWorkspaceHost _remoteLanguageServiceWorkspaceHost; private readonly Dictionary<string, ProjectId> _projects = new Dictionary<string, ProjectId>(); public ProjectId GetProject(string projectName) { if (_projects.TryGetValue(projectName, out var projectId)) { return projectId; } var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectName), VersionStamp.Default, projectName, projectName, LanguageNames.CSharp); _remoteLanguageServiceWorkspaceHost.Workspace.OnProjectAdded(projectInfo); _projects.Add(projectName, projectInfo.Id); return projectInfo.Id; } public CodeAnalysis.Workspace Workspace => _remoteLanguageServiceWorkspaceHost.Workspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspRazorProjectFactory(RemoteLanguageServiceWorkspaceHost remoteLanguageServiceWorkspaceHost) => _remoteLanguageServiceWorkspaceHost = remoteLanguageServiceWorkspaceHost ?? throw new ArgumentNullException(nameof(remoteLanguageServiceWorkspaceHost)); } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isUnsafe: symbol.RequiresUnsafeModifier(), isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed); } /// <summary> /// Checks a given symbol for browsability based on its declaration location, attributes /// explicitly limiting browsability, and whether showing of advanced members is enabled. /// The optional editorBrowsableInfo parameters may be used to specify the symbols of the /// constructors of the various browsability limiting attributes because finding these /// repeatedly over a large list of symbols can be slow. If these are not provided, /// they will be found in the compilation. /// </summary> public static bool IsEditorBrowsable( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { return IsEditorBrowsableWithState( symbol, hideAdvancedMembers, compilation, editorBrowsableInfo).isBrowsable; } // In addition to given symbol's browsability, also returns its EditorBrowsableState if it contains EditorBrowsableAttribute. public static (bool isBrowsable, bool isEditorBrowsableStateAdvanced) IsEditorBrowsableWithState( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { // Namespaces can't have attributes, so just return true here. This also saves us a // costly check if this namespace has any locations in source (since a merged namespace // needs to go collect all the locations). if (symbol.Kind == SymbolKind.Namespace) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } // check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types. // This saves a few percent in typing scenarios. An implicitly declared symbol can't // have attributes, so it can't be hidden by them. if (symbol.IsImplicitlyDeclared) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } if (editorBrowsableInfo.IsDefault) { editorBrowsableInfo = new EditorBrowsableInfo(compilation); } // Ignore browsability limiting attributes if the symbol is declared in source. // Check all locations since some of VB's embedded My symbols are declared in // both source and the MyTemplateLocation. if (symbol.Locations.All(loc => loc.IsInSource)) { // The HideModuleNameAttribute still applies to Modules defined in source return (!IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute), isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibited(symbol, hideAdvancedMembers, editorBrowsableInfo); return (!isProhibited, isEditorBrowsableStateAdvanced); } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibited( ISymbol symbol, bool hideAdvancedMembers, EditorBrowsableInfo editorBrowsableInfo) { var attributes = symbol.GetAttributes(); if (attributes.Length == 0) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibitedByEditorBrowsableAttribute(attributes, hideAdvancedMembers, editorBrowsableInfo.EditorBrowsableAttributeConstructor); return ((isProhibited || IsBrowsingProhibitedByTypeLibTypeAttribute(attributes, editorBrowsableInfo.TypeLibTypeAttributeConstructors) || IsBrowsingProhibitedByTypeLibFuncAttribute(attributes, editorBrowsableInfo.TypeLibFuncAttributeConstructors) || IsBrowsingProhibitedByTypeLibVarAttribute(attributes, editorBrowsableInfo.TypeLibVarAttributeConstructors) || IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute, attributes)), isEditorBrowsableStateAdvanced); } private static bool IsBrowsingProhibitedByHideModuleNameAttribute( ISymbol symbol, INamedTypeSymbol? hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default) { if (hideModuleNameAttribute == null || !symbol.IsModuleType()) { return false; } attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes; foreach (var attribute in attributes) { if (Equals(attribute.AttributeClass, hideModuleNameAttribute)) { return true; } } return false; } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibitedByEditorBrowsableAttribute( ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, IMethodSymbol? constructor) { if (constructor == null) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } foreach (var attribute in attributes) { if (Equals(attribute.AttributeConstructor, constructor) && attribute.ConstructorArguments.Length == 1 && attribute.ConstructorArguments.First().Value is int) { #nullable disable // Should use unboxed value from previous 'is int' https://github.com/dotnet/roslyn/issues/39166 var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value; #nullable enable if (EditorBrowsableState.Never == state) { return (isProhibited: true, isEditorBrowsableStateAdvanced: false); } if (EditorBrowsableState.Advanced == state) { return (isProhibited: hideAdvancedMembers, isEditorBrowsableStateAdvanced: true); } } } return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } private static bool IsBrowsingProhibitedByTypeLibTypeAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibTypeFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibFuncAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibFuncFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibVarAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibVarFlagsFHidden); } private const int TypeLibTypeFlagsFHidden = 0x0010; private const int TypeLibFuncFlagsFHidden = 0x0040; private const int TypeLibVarFlagsFHidden = 0x0040; private static bool IsBrowsingProhibitedByTypeLibAttributeWorker( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> attributeConstructors, int hiddenFlag) { foreach (var attribute in attributes) { if (attribute.ConstructorArguments.Length == 1) { foreach (var constructor in attributeConstructors) { if (Equals(attribute.AttributeConstructor, constructor)) { // Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument. var argumentValue = attribute.ConstructorArguments.First().Value; int actualFlags; if (argumentValue is int i) { actualFlags = i; } else if (argumentValue is short sh) { actualFlags = sh; } else { continue; } if ((actualFlags & hiddenFlag) == hiddenFlag) { return true; } } } } } return false; } public static DocumentationComment GetDocumentationComment(this ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default) => GetDocumentationComment(symbol, visitedSymbols: null, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken); private static DocumentationComment GetDocumentationComment(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, CultureInfo? preferredCulture, bool expandIncludes, bool expandInheritdoc, CancellationToken cancellationToken) { var xmlText = symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); if (expandInheritdoc) { if (string.IsNullOrEmpty(xmlText)) { if (IsEligibleForAutomaticInheritdoc(symbol)) { xmlText = $@"<doc><inheritdoc/></doc>"; } else { return DocumentationComment.Empty; } } try { var element = XElement.Parse(xmlText, LoadOptions.PreserveWhitespace); element.ReplaceNodes(RewriteMany(symbol, visitedSymbols, compilation, element.Nodes().ToArray(), cancellationToken)); xmlText = element.ToString(SaveOptions.DisableFormatting); } catch (XmlException) { // Malformed documentation comments will produce an exception during parsing. This is not directly // actionable, so avoid the overhead of telemetry reporting for it. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1385578 } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } } return RoslynString.IsNullOrEmpty(xmlText) ? DocumentationComment.Empty : DocumentationComment.FromXmlFragment(xmlText); static bool IsEligibleForAutomaticInheritdoc(ISymbol symbol) { // Only the following symbols are eligible to inherit documentation without an <inheritdoc/> element: // // * Members that override an inherited member // * Members that implement an interface member if (symbol.IsOverride) { return true; } if (symbol.ContainingType is null) { // Observed with certain implicit operators, such as operator==(void*, void*). return false; } switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (symbol.ExplicitOrImplicitInterfaceImplementations().Any()) { return true; } break; default: break; } return false; } } private static XNode[] RewriteInheritdocElements(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode node, CancellationToken cancellationToken) { if (node.NodeType == XmlNodeType.Element) { var element = (XElement)node; if (ElementNameIs(element, DocumentationCommentXmlNames.InheritdocElementName)) { var rewritten = RewriteInheritdocElement(symbol, visitedSymbols, compilation, element, cancellationToken); if (rewritten is object) { return rewritten; } } } var container = node as XContainer; if (container == null) { return new XNode[] { Copy(node, copyAttributeAnnotations: false) }; } var oldNodes = container.Nodes(); // Do this after grabbing the nodes, so we don't see copies of them. container = Copy(container, copyAttributeAnnotations: false); // WARN: don't use node after this point - use container since it's already been copied. if (oldNodes != null) { var rewritten = RewriteMany(symbol, visitedSymbols, compilation, oldNodes.ToArray(), cancellationToken); container.ReplaceNodes(rewritten); } return new XNode[] { container }; } private static XNode[] RewriteMany(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode[] nodes, CancellationToken cancellationToken) { var result = new List<XNode>(); foreach (var child in nodes) { result.AddRange(RewriteInheritdocElements(symbol, visitedSymbols, compilation, child, cancellationToken)); } return result.ToArray(); } private static XNode[]? RewriteInheritdocElement(ISymbol memberSymbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XElement element, CancellationToken cancellationToken) { var crefAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.CrefAttributeName)); var pathAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); var candidate = GetCandidateSymbol(memberSymbol); var hasCandidateCref = candidate is object; var hasCrefAttribute = crefAttribute is object; var hasPathAttribute = pathAttribute is object; if (!hasCrefAttribute && !hasCandidateCref) { // No cref available return null; } ISymbol? symbol; if (crefAttribute is null) { Contract.ThrowIfNull(candidate); symbol = candidate; } else { var crefValue = crefAttribute.Value; symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefValue, compilation); if (symbol is null) { return null; } } visitedSymbols ??= new HashSet<ISymbol>(); if (!visitedSymbols.Add(symbol)) { // Prevent recursion return null; } try { var inheritedDocumentation = GetDocumentationComment(symbol, visitedSymbols, compilation, preferredCulture: null, expandIncludes: true, expandInheritdoc: true, cancellationToken); if (inheritedDocumentation == DocumentationComment.Empty) { return Array.Empty<XNode>(); } var document = XDocument.Parse(inheritedDocumentation.FullXmlFragment); string xpathValue; if (string.IsNullOrEmpty(pathAttribute?.Value)) { xpathValue = BuildXPathForElement(element.Parent!); } else { xpathValue = pathAttribute!.Value; if (xpathValue.StartsWith("/")) { // Account for the root <doc> or <member> element xpathValue = "/*" + xpathValue; } } // Consider the following code, we want Test<int>.Clone to say "Clones a Test<int>" instead of "Clones a int", thus // we rewrite `typeparamref`s as cref pointing to the correct type: /* public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name="T">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name="T"/>.</summary> public T Clone(); } */ // Note: there is no way to cref an instantiated generic type. See https://github.com/dotnet/csharplang/issues/401 var typeParameterRefs = document.Descendants(DocumentationCommentXmlNames.TypeParameterReferenceElementName).ToImmutableArray(); foreach (var typeParameterRef in typeParameterRefs) { if (typeParameterRef.Attribute(DocumentationCommentXmlNames.NameAttributeName) is var typeParamName) { var index = symbol.OriginalDefinition.GetAllTypeParameters().IndexOf(p => p.Name == typeParamName.Value); if (index >= 0) { var typeArgs = symbol.GetAllTypeArguments(); if (index < typeArgs.Length) { var docId = typeArgs[index].GetDocumentationCommentId(); var replacement = new XElement(DocumentationCommentXmlNames.SeeElementName); replacement.SetAttributeValue(DocumentationCommentXmlNames.CrefAttributeName, docId); typeParameterRef.ReplaceWith(replacement); } } } } var loadedElements = TrySelectNodes(document, xpathValue); return loadedElements ?? Array.Empty<XNode>(); } catch (XmlException) { return Array.Empty<XNode>(); } finally { visitedSymbols.Remove(symbol); } // Local functions static ISymbol? GetCandidateSymbol(ISymbol memberSymbol) { if (memberSymbol.ExplicitInterfaceImplementations().Any()) { return memberSymbol.ExplicitInterfaceImplementations().First(); } else if (memberSymbol.IsOverride) { return memberSymbol.GetOverriddenMember(); } if (memberSymbol is IMethodSymbol methodSymbol) { if (methodSymbol.MethodKind is MethodKind.Constructor or MethodKind.StaticConstructor) { var baseType = memberSymbol.ContainingType.BaseType; #nullable disable // Can 'baseType' be null here? https://github.com/dotnet/roslyn/issues/39166 return baseType.Constructors.Where(c => IsSameSignature(methodSymbol, c)).FirstOrDefault(); #nullable enable } else { // check for implicit interface return methodSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } } else if (memberSymbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Class) { // Classes use the base type as the default inheritance candidate. A different target (e.g. an // interface) can be provided via the 'path' attribute. return typeSymbol.BaseType; } else if (typeSymbol.TypeKind == TypeKind.Interface) { return typeSymbol.Interfaces.FirstOrDefault(); } else { // This includes structs, enums, and delegates as mentioned in the inheritdoc spec return null; } } return memberSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } static bool IsSameSignature(IMethodSymbol left, IMethodSymbol right) { if (left.Parameters.Length != right.Parameters.Length) { return false; } if (left.IsStatic != right.IsStatic) { return false; } if (!left.ReturnType.Equals(right.ReturnType)) { return false; } for (var i = 0; i < left.Parameters.Length; i++) { if (!left.Parameters[i].Type.Equals(right.Parameters[i].Type)) { return false; } } return true; } static string BuildXPathForElement(XElement element) { if (ElementNameIs(element, "member") || ElementNameIs(element, "doc")) { // Avoid string concatenation allocations for inheritdoc as a top-level element return "/*/node()[not(self::overloads)]"; } var path = "/node()[not(self::overloads)]"; for (var current = element; current != null; current = current.Parent) { var currentName = current.Name.ToString(); if (ElementNameIs(current, "member") || ElementNameIs(current, "doc")) { // Allow <member> and <doc> to be used interchangeably currentName = "*"; } path = "/" + currentName + path; } return path; } } private static TNode Copy<TNode>(TNode node, bool copyAttributeAnnotations) where TNode : XNode { XNode copy; // Documents can't be added to containers, so our usual copy trick won't work. if (node.NodeType == XmlNodeType.Document) { copy = new XDocument(((XDocument)(object)node)); } else { XContainer temp = new XElement("temp"); temp.Add(node); copy = temp.LastNode!; temp.RemoveNodes(); } Debug.Assert(copy != node); Debug.Assert(copy.Parent == null); // Otherwise, when we give it one, it will be copied. // Copy annotations, the above doesn't preserve them. // We need to preserve Location annotations as well as line position annotations. CopyAnnotations(node, copy); // We also need to preserve line position annotations for all attributes // since we report errors with attribute locations. if (copyAttributeAnnotations && node.NodeType == XmlNodeType.Element) { var sourceElement = (XElement)(object)node; var targetElement = (XElement)copy; var sourceAttributes = sourceElement.Attributes().GetEnumerator(); var targetAttributes = targetElement.Attributes().GetEnumerator(); while (sourceAttributes.MoveNext() && targetAttributes.MoveNext()) { Debug.Assert(sourceAttributes.Current.Name == targetAttributes.Current.Name); CopyAnnotations(sourceAttributes.Current, targetAttributes.Current); } } return (TNode)copy; } private static void CopyAnnotations(XObject source, XObject target) { foreach (var annotation in source.Annotations<object>()) { target.AddAnnotation(annotation); } } private static XNode[]? TrySelectNodes(XNode node, string xpath) { try { var xpathResult = (IEnumerable)System.Xml.XPath.Extensions.XPathEvaluate(node, xpath); // Throws InvalidOperationException if the result of the XPath is an XDocument: return xpathResult?.Cast<XNode>().ToArray(); } catch (InvalidOperationException) { return null; } catch (XPathException) { return null; } } private static bool ElementNameIs(XElement element, string name) => string.IsNullOrEmpty(element.Name.NamespaceName) && DocumentationCommentXmlNames.ElementEquals(element.Name.LocalName, name); /// <summary> /// First, remove symbols from the set if they are overridden by other symbols in the set. /// If a symbol is overridden only by symbols outside of the set, then it is not removed. /// This is useful for filtering out symbols that cannot be accessed in a given context due /// to the existence of overriding members. Second, remove remaining symbols that are /// unsupported (e.g. pointer types in VB) or not editor browsable based on the EditorBrowsable /// attribute. /// </summary> public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { symbols = symbols.RemoveOverriddenSymbolsWithinSet(); // Since all symbols are from the same compilation, find the required attribute // constructors once and reuse. var editorBrowsableInfo = new EditorBrowsableInfo(compilation); // PERF: HasUnsupportedMetadata may require recreating the syntax tree to get the base class, so first // check to see if we're referencing a symbol defined in source. static bool isSymbolDefinedInSource(Location l) => l.IsInSource; return symbols.WhereAsArray((s, arg) => (s.Locations.Any(isSymbolDefinedInSource) || !s.HasUnsupportedMetadata) && !s.IsDestructor() && s.IsEditorBrowsable( arg.hideAdvancedMembers, arg.editorBrowsableInfo.Compilation, arg.editorBrowsableInfo), (hideAdvancedMembers, editorBrowsableInfo)); } private static ImmutableArray<T> RemoveOverriddenSymbolsWithinSet<T>(this ImmutableArray<T> symbols) where T : ISymbol { var overriddenSymbols = new HashSet<ISymbol>(); foreach (var symbol in symbols) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null && !overriddenSymbols.Contains(overriddenMember)) overriddenSymbols.Add(overriddenMember); } return symbols.WhereAsArray(s => !overriddenSymbols.Contains(s)); } public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { return symbols.FilterToVisibleAndBrowsableSymbols(hideAdvancedMembers, compilation) .WhereAsArray(s => !s.RequiresUnsafeModifier()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isUnsafe: symbol.RequiresUnsafeModifier(), isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed); } /// <summary> /// Checks a given symbol for browsability based on its declaration location, attributes /// explicitly limiting browsability, and whether showing of advanced members is enabled. /// The optional editorBrowsableInfo parameters may be used to specify the symbols of the /// constructors of the various browsability limiting attributes because finding these /// repeatedly over a large list of symbols can be slow. If these are not provided, /// they will be found in the compilation. /// </summary> public static bool IsEditorBrowsable( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { return IsEditorBrowsableWithState( symbol, hideAdvancedMembers, compilation, editorBrowsableInfo).isBrowsable; } // In addition to given symbol's browsability, also returns its EditorBrowsableState if it contains EditorBrowsableAttribute. public static (bool isBrowsable, bool isEditorBrowsableStateAdvanced) IsEditorBrowsableWithState( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { // Namespaces can't have attributes, so just return true here. This also saves us a // costly check if this namespace has any locations in source (since a merged namespace // needs to go collect all the locations). if (symbol.Kind == SymbolKind.Namespace) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } // check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types. // This saves a few percent in typing scenarios. An implicitly declared symbol can't // have attributes, so it can't be hidden by them. if (symbol.IsImplicitlyDeclared) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } if (editorBrowsableInfo.IsDefault) { editorBrowsableInfo = new EditorBrowsableInfo(compilation); } // Ignore browsability limiting attributes if the symbol is declared in source. // Check all locations since some of VB's embedded My symbols are declared in // both source and the MyTemplateLocation. if (symbol.Locations.All(loc => loc.IsInSource)) { // The HideModuleNameAttribute still applies to Modules defined in source return (!IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute), isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibited(symbol, hideAdvancedMembers, editorBrowsableInfo); return (!isProhibited, isEditorBrowsableStateAdvanced); } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibited( ISymbol symbol, bool hideAdvancedMembers, EditorBrowsableInfo editorBrowsableInfo) { var attributes = symbol.GetAttributes(); if (attributes.Length == 0) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibitedByEditorBrowsableAttribute(attributes, hideAdvancedMembers, editorBrowsableInfo.EditorBrowsableAttributeConstructor); return ((isProhibited || IsBrowsingProhibitedByTypeLibTypeAttribute(attributes, editorBrowsableInfo.TypeLibTypeAttributeConstructors) || IsBrowsingProhibitedByTypeLibFuncAttribute(attributes, editorBrowsableInfo.TypeLibFuncAttributeConstructors) || IsBrowsingProhibitedByTypeLibVarAttribute(attributes, editorBrowsableInfo.TypeLibVarAttributeConstructors) || IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute, attributes)), isEditorBrowsableStateAdvanced); } private static bool IsBrowsingProhibitedByHideModuleNameAttribute( ISymbol symbol, INamedTypeSymbol? hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default) { if (hideModuleNameAttribute == null || !symbol.IsModuleType()) { return false; } attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes; foreach (var attribute in attributes) { if (Equals(attribute.AttributeClass, hideModuleNameAttribute)) { return true; } } return false; } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibitedByEditorBrowsableAttribute( ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, IMethodSymbol? constructor) { if (constructor == null) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } foreach (var attribute in attributes) { if (Equals(attribute.AttributeConstructor, constructor) && attribute.ConstructorArguments.Length == 1 && attribute.ConstructorArguments.First().Value is int) { #nullable disable // Should use unboxed value from previous 'is int' https://github.com/dotnet/roslyn/issues/39166 var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value; #nullable enable if (EditorBrowsableState.Never == state) { return (isProhibited: true, isEditorBrowsableStateAdvanced: false); } if (EditorBrowsableState.Advanced == state) { return (isProhibited: hideAdvancedMembers, isEditorBrowsableStateAdvanced: true); } } } return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } private static bool IsBrowsingProhibitedByTypeLibTypeAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibTypeFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibFuncAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibFuncFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibVarAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibVarFlagsFHidden); } private const int TypeLibTypeFlagsFHidden = 0x0010; private const int TypeLibFuncFlagsFHidden = 0x0040; private const int TypeLibVarFlagsFHidden = 0x0040; private static bool IsBrowsingProhibitedByTypeLibAttributeWorker( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> attributeConstructors, int hiddenFlag) { foreach (var attribute in attributes) { if (attribute.ConstructorArguments.Length == 1) { foreach (var constructor in attributeConstructors) { if (Equals(attribute.AttributeConstructor, constructor)) { // Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument. var argumentValue = attribute.ConstructorArguments.First().Value; int actualFlags; if (argumentValue is int i) { actualFlags = i; } else if (argumentValue is short sh) { actualFlags = sh; } else { continue; } if ((actualFlags & hiddenFlag) == hiddenFlag) { return true; } } } } } return false; } public static DocumentationComment GetDocumentationComment(this ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default) => GetDocumentationComment(symbol, visitedSymbols: null, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken); private static DocumentationComment GetDocumentationComment(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, CultureInfo? preferredCulture, bool expandIncludes, bool expandInheritdoc, CancellationToken cancellationToken) { var xmlText = symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); if (expandInheritdoc) { if (string.IsNullOrEmpty(xmlText)) { if (IsEligibleForAutomaticInheritdoc(symbol)) { xmlText = $@"<doc><inheritdoc/></doc>"; } else { return DocumentationComment.Empty; } } try { var element = XElement.Parse(xmlText, LoadOptions.PreserveWhitespace); element.ReplaceNodes(RewriteMany(symbol, visitedSymbols, compilation, element.Nodes().ToArray(), cancellationToken)); xmlText = element.ToString(SaveOptions.DisableFormatting); } catch (XmlException) { // Malformed documentation comments will produce an exception during parsing. This is not directly // actionable, so avoid the overhead of telemetry reporting for it. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1385578 } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } } return RoslynString.IsNullOrEmpty(xmlText) ? DocumentationComment.Empty : DocumentationComment.FromXmlFragment(xmlText); static bool IsEligibleForAutomaticInheritdoc(ISymbol symbol) { // Only the following symbols are eligible to inherit documentation without an <inheritdoc/> element: // // * Members that override an inherited member // * Members that implement an interface member if (symbol.IsOverride) { return true; } if (symbol.ContainingType is null) { // Observed with certain implicit operators, such as operator==(void*, void*). return false; } switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (symbol.ExplicitOrImplicitInterfaceImplementations().Any()) { return true; } break; default: break; } return false; } } private static XNode[] RewriteInheritdocElements(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode node, CancellationToken cancellationToken) { if (node.NodeType == XmlNodeType.Element) { var element = (XElement)node; if (ElementNameIs(element, DocumentationCommentXmlNames.InheritdocElementName)) { var rewritten = RewriteInheritdocElement(symbol, visitedSymbols, compilation, element, cancellationToken); if (rewritten is object) { return rewritten; } } } var container = node as XContainer; if (container == null) { return new XNode[] { Copy(node, copyAttributeAnnotations: false) }; } var oldNodes = container.Nodes(); // Do this after grabbing the nodes, so we don't see copies of them. container = Copy(container, copyAttributeAnnotations: false); // WARN: don't use node after this point - use container since it's already been copied. if (oldNodes != null) { var rewritten = RewriteMany(symbol, visitedSymbols, compilation, oldNodes.ToArray(), cancellationToken); container.ReplaceNodes(rewritten); } return new XNode[] { container }; } private static XNode[] RewriteMany(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode[] nodes, CancellationToken cancellationToken) { var result = new List<XNode>(); foreach (var child in nodes) { result.AddRange(RewriteInheritdocElements(symbol, visitedSymbols, compilation, child, cancellationToken)); } return result.ToArray(); } private static XNode[]? RewriteInheritdocElement(ISymbol memberSymbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XElement element, CancellationToken cancellationToken) { var crefAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.CrefAttributeName)); var pathAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); var candidate = GetCandidateSymbol(memberSymbol); var hasCandidateCref = candidate is object; var hasCrefAttribute = crefAttribute is object; var hasPathAttribute = pathAttribute is object; if (!hasCrefAttribute && !hasCandidateCref) { // No cref available return null; } ISymbol? symbol; if (crefAttribute is null) { Contract.ThrowIfNull(candidate); symbol = candidate; } else { var crefValue = crefAttribute.Value; symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefValue, compilation); if (symbol is null) { return null; } } visitedSymbols ??= new HashSet<ISymbol>(); if (!visitedSymbols.Add(symbol)) { // Prevent recursion return null; } try { var inheritedDocumentation = GetDocumentationComment(symbol, visitedSymbols, compilation, preferredCulture: null, expandIncludes: true, expandInheritdoc: true, cancellationToken); if (inheritedDocumentation == DocumentationComment.Empty) { return Array.Empty<XNode>(); } var document = XDocument.Parse(inheritedDocumentation.FullXmlFragment); string xpathValue; if (string.IsNullOrEmpty(pathAttribute?.Value)) { xpathValue = BuildXPathForElement(element.Parent!); } else { xpathValue = pathAttribute!.Value; if (xpathValue.StartsWith("/")) { // Account for the root <doc> or <member> element xpathValue = "/*" + xpathValue; } } // Consider the following code, we want Test<int>.Clone to say "Clones a Test<int>" instead of "Clones a int", thus // we rewrite `typeparamref`s as cref pointing to the correct type: /* public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name="T">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name="T"/>.</summary> public T Clone(); } */ // Note: there is no way to cref an instantiated generic type. See https://github.com/dotnet/csharplang/issues/401 var typeParameterRefs = document.Descendants(DocumentationCommentXmlNames.TypeParameterReferenceElementName).ToImmutableArray(); foreach (var typeParameterRef in typeParameterRefs) { if (typeParameterRef.Attribute(DocumentationCommentXmlNames.NameAttributeName) is var typeParamName) { var index = symbol.OriginalDefinition.GetAllTypeParameters().IndexOf(p => p.Name == typeParamName.Value); if (index >= 0) { var typeArgs = symbol.GetAllTypeArguments(); if (index < typeArgs.Length) { var docId = typeArgs[index].GetDocumentationCommentId(); var replacement = new XElement(DocumentationCommentXmlNames.SeeElementName); replacement.SetAttributeValue(DocumentationCommentXmlNames.CrefAttributeName, docId); typeParameterRef.ReplaceWith(replacement); } } } } var loadedElements = TrySelectNodes(document, xpathValue); return loadedElements ?? Array.Empty<XNode>(); } catch (XmlException) { return Array.Empty<XNode>(); } finally { visitedSymbols.Remove(symbol); } // Local functions static ISymbol? GetCandidateSymbol(ISymbol memberSymbol) { if (memberSymbol.ExplicitInterfaceImplementations().Any()) { return memberSymbol.ExplicitInterfaceImplementations().First(); } else if (memberSymbol.IsOverride) { return memberSymbol.GetOverriddenMember(); } if (memberSymbol is IMethodSymbol methodSymbol) { if (methodSymbol.MethodKind is MethodKind.Constructor or MethodKind.StaticConstructor) { var baseType = memberSymbol.ContainingType.BaseType; #nullable disable // Can 'baseType' be null here? https://github.com/dotnet/roslyn/issues/39166 return baseType.Constructors.Where(c => IsSameSignature(methodSymbol, c)).FirstOrDefault(); #nullable enable } else { // check for implicit interface return methodSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } } else if (memberSymbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Class) { // Classes use the base type as the default inheritance candidate. A different target (e.g. an // interface) can be provided via the 'path' attribute. return typeSymbol.BaseType; } else if (typeSymbol.TypeKind == TypeKind.Interface) { return typeSymbol.Interfaces.FirstOrDefault(); } else { // This includes structs, enums, and delegates as mentioned in the inheritdoc spec return null; } } return memberSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } static bool IsSameSignature(IMethodSymbol left, IMethodSymbol right) { if (left.Parameters.Length != right.Parameters.Length) { return false; } if (left.IsStatic != right.IsStatic) { return false; } if (!left.ReturnType.Equals(right.ReturnType)) { return false; } for (var i = 0; i < left.Parameters.Length; i++) { if (!left.Parameters[i].Type.Equals(right.Parameters[i].Type)) { return false; } } return true; } static string BuildXPathForElement(XElement element) { if (ElementNameIs(element, "member") || ElementNameIs(element, "doc")) { // Avoid string concatenation allocations for inheritdoc as a top-level element return "/*/node()[not(self::overloads)]"; } var path = "/node()[not(self::overloads)]"; for (var current = element; current != null; current = current.Parent) { var currentName = current.Name.ToString(); if (ElementNameIs(current, "member") || ElementNameIs(current, "doc")) { // Allow <member> and <doc> to be used interchangeably currentName = "*"; } path = "/" + currentName + path; } return path; } } private static TNode Copy<TNode>(TNode node, bool copyAttributeAnnotations) where TNode : XNode { XNode copy; // Documents can't be added to containers, so our usual copy trick won't work. if (node.NodeType == XmlNodeType.Document) { copy = new XDocument(((XDocument)(object)node)); } else { XContainer temp = new XElement("temp"); temp.Add(node); copy = temp.LastNode!; temp.RemoveNodes(); } Debug.Assert(copy != node); Debug.Assert(copy.Parent == null); // Otherwise, when we give it one, it will be copied. // Copy annotations, the above doesn't preserve them. // We need to preserve Location annotations as well as line position annotations. CopyAnnotations(node, copy); // We also need to preserve line position annotations for all attributes // since we report errors with attribute locations. if (copyAttributeAnnotations && node.NodeType == XmlNodeType.Element) { var sourceElement = (XElement)(object)node; var targetElement = (XElement)copy; var sourceAttributes = sourceElement.Attributes().GetEnumerator(); var targetAttributes = targetElement.Attributes().GetEnumerator(); while (sourceAttributes.MoveNext() && targetAttributes.MoveNext()) { Debug.Assert(sourceAttributes.Current.Name == targetAttributes.Current.Name); CopyAnnotations(sourceAttributes.Current, targetAttributes.Current); } } return (TNode)copy; } private static void CopyAnnotations(XObject source, XObject target) { foreach (var annotation in source.Annotations<object>()) { target.AddAnnotation(annotation); } } private static XNode[]? TrySelectNodes(XNode node, string xpath) { try { var xpathResult = (IEnumerable)System.Xml.XPath.Extensions.XPathEvaluate(node, xpath); // Throws InvalidOperationException if the result of the XPath is an XDocument: return xpathResult?.Cast<XNode>().ToArray(); } catch (InvalidOperationException) { return null; } catch (XPathException) { return null; } } private static bool ElementNameIs(XElement element, string name) => string.IsNullOrEmpty(element.Name.NamespaceName) && DocumentationCommentXmlNames.ElementEquals(element.Name.LocalName, name); /// <summary> /// First, remove symbols from the set if they are overridden by other symbols in the set. /// If a symbol is overridden only by symbols outside of the set, then it is not removed. /// This is useful for filtering out symbols that cannot be accessed in a given context due /// to the existence of overriding members. Second, remove remaining symbols that are /// unsupported (e.g. pointer types in VB) or not editor browsable based on the EditorBrowsable /// attribute. /// </summary> public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { symbols = symbols.RemoveOverriddenSymbolsWithinSet(); // Since all symbols are from the same compilation, find the required attribute // constructors once and reuse. var editorBrowsableInfo = new EditorBrowsableInfo(compilation); // PERF: HasUnsupportedMetadata may require recreating the syntax tree to get the base class, so first // check to see if we're referencing a symbol defined in source. static bool isSymbolDefinedInSource(Location l) => l.IsInSource; return symbols.WhereAsArray((s, arg) => (s.Locations.Any(isSymbolDefinedInSource) || !s.HasUnsupportedMetadata) && !s.IsDestructor() && s.IsEditorBrowsable( arg.hideAdvancedMembers, arg.editorBrowsableInfo.Compilation, arg.editorBrowsableInfo), (hideAdvancedMembers, editorBrowsableInfo)); } private static ImmutableArray<T> RemoveOverriddenSymbolsWithinSet<T>(this ImmutableArray<T> symbols) where T : ISymbol { var overriddenSymbols = new HashSet<ISymbol>(); foreach (var symbol in symbols) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null && !overriddenSymbols.Contains(overriddenMember)) overriddenSymbols.Add(overriddenMember); } return symbols.WhereAsArray(s => !overriddenSymbols.Contains(s)); } public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { return symbols.FilterToVisibleAndBrowsableSymbols(hideAdvancedMembers, compilation) .WhereAsArray(s => !s.RequiresUnsafeModifier()); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedMethodSymbol : AbstractWrappedSymbol, IMethodSymbol { private readonly IMethodSymbol _symbol; public WrappedMethodSymbol(IMethodSymbol methodSymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(methodSymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = methodSymbol; } public int Arity => _symbol.Arity; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public INamedTypeSymbol AssociatedAnonymousDelegate => _symbol.AssociatedAnonymousDelegate; public IMethodSymbol ConstructedFrom => _symbol.ConstructedFrom; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsInitOnly => _symbol.IsInitOnly; public System.Reflection.MethodImplAttributes MethodImplementationFlags => _symbol.MethodImplementationFlags; public ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IMethodSymbol>() : _symbol.ExplicitInterfaceImplementations; } } public bool HidesBaseMethodsByName => _symbol.HidesBaseMethodsByName; public bool IsExtensionMethod => _symbol.IsExtensionMethod; public bool IsGenericMethod => _symbol.IsGenericMethod; public bool IsAsync => _symbol.IsAsync; public MethodKind MethodKind => _symbol.MethodKind; public new IMethodSymbol OriginalDefinition { get { return this; } } public IMethodSymbol OverriddenMethod => _symbol.OverriddenMethod; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol PartialDefinitionPart => _symbol.PartialDefinitionPart; public IMethodSymbol PartialImplementationPart => _symbol.PartialImplementationPart; public bool IsPartialDefinition => _symbol.IsPartialDefinition; public ITypeSymbol ReceiverType => _symbol.ReceiverType; public NullableAnnotation ReceiverNullableAnnotation => _symbol.ReceiverNullableAnnotation; public IMethodSymbol ReducedFrom => // This implementation feels incorrect! _symbol.ReducedFrom; public ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { // This implementation feels incorrect, but it follows the pattern that other extension method related APIs are using! return _symbol.GetTypeInferredDuringReduction(reducedFromTypeParameter); } public bool ReturnsVoid => _symbol.ReturnsVoid; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public ITypeSymbol ReturnType => _symbol.ReturnType; public NullableAnnotation ReturnNullableAnnotation => _symbol.ReturnNullableAnnotation; public ImmutableArray<AttributeData> GetReturnTypeAttributes() => _symbol.GetReturnTypeAttributes(); public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> ReturnTypeCustomModifiers => _symbol.ReturnTypeCustomModifiers; public ImmutableArray<ITypeSymbol> TypeArguments => _symbol.TypeArguments; public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => _symbol.TypeArgumentNullableAnnotations; public ImmutableArray<ITypeParameterSymbol> TypeParameters => _symbol.TypeParameters; public IMethodSymbol Construct(params ITypeSymbol[] typeArguments) => _symbol.Construct(typeArguments); public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) => _symbol.Construct(typeArguments, typeArgumentNullableAnnotations); public DllImportData GetDllImportData() => _symbol.GetDllImportData(); public IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) { // This implementation feels incorrect! return _symbol.ReduceExtensionMethod(receiverType); } public bool IsVararg => _symbol.IsVararg; public bool IsCheckedBuiltin => _symbol.IsCheckedBuiltin; public bool IsConditional => _symbol.IsConditional; public SignatureCallingConvention CallingConvention => _symbol.CallingConvention; public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => _symbol.UnmanagedCallingConventionTypes; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private class WrappedMethodSymbol : AbstractWrappedSymbol, IMethodSymbol { private readonly IMethodSymbol _symbol; public WrappedMethodSymbol(IMethodSymbol methodSymbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(methodSymbol, canImplementImplicitly, docCommentFormattingService) { _symbol = methodSymbol; } public int Arity => _symbol.Arity; public ISymbol AssociatedSymbol => _symbol.AssociatedSymbol; public INamedTypeSymbol AssociatedAnonymousDelegate => _symbol.AssociatedAnonymousDelegate; public IMethodSymbol ConstructedFrom => _symbol.ConstructedFrom; public bool IsReadOnly => _symbol.IsReadOnly; public bool IsInitOnly => _symbol.IsInitOnly; public System.Reflection.MethodImplAttributes MethodImplementationFlags => _symbol.MethodImplementationFlags; public ImmutableArray<IMethodSymbol> ExplicitInterfaceImplementations { get { return CanImplementImplicitly ? ImmutableArray.Create<IMethodSymbol>() : _symbol.ExplicitInterfaceImplementations; } } public bool HidesBaseMethodsByName => _symbol.HidesBaseMethodsByName; public bool IsExtensionMethod => _symbol.IsExtensionMethod; public bool IsGenericMethod => _symbol.IsGenericMethod; public bool IsAsync => _symbol.IsAsync; public MethodKind MethodKind => _symbol.MethodKind; public new IMethodSymbol OriginalDefinition { get { return this; } } public IMethodSymbol OverriddenMethod => _symbol.OverriddenMethod; public ImmutableArray<IParameterSymbol> Parameters => _symbol.Parameters; public IMethodSymbol PartialDefinitionPart => _symbol.PartialDefinitionPart; public IMethodSymbol PartialImplementationPart => _symbol.PartialImplementationPart; public bool IsPartialDefinition => _symbol.IsPartialDefinition; public ITypeSymbol ReceiverType => _symbol.ReceiverType; public NullableAnnotation ReceiverNullableAnnotation => _symbol.ReceiverNullableAnnotation; public IMethodSymbol ReducedFrom => // This implementation feels incorrect! _symbol.ReducedFrom; public ITypeSymbol GetTypeInferredDuringReduction(ITypeParameterSymbol reducedFromTypeParameter) { // This implementation feels incorrect, but it follows the pattern that other extension method related APIs are using! return _symbol.GetTypeInferredDuringReduction(reducedFromTypeParameter); } public bool ReturnsVoid => _symbol.ReturnsVoid; public bool ReturnsByRef => _symbol.ReturnsByRef; public bool ReturnsByRefReadonly => _symbol.ReturnsByRefReadonly; public RefKind RefKind => _symbol.RefKind; public ITypeSymbol ReturnType => _symbol.ReturnType; public NullableAnnotation ReturnNullableAnnotation => _symbol.ReturnNullableAnnotation; public ImmutableArray<AttributeData> GetReturnTypeAttributes() => _symbol.GetReturnTypeAttributes(); public ImmutableArray<CustomModifier> RefCustomModifiers => _symbol.RefCustomModifiers; public ImmutableArray<CustomModifier> ReturnTypeCustomModifiers => _symbol.ReturnTypeCustomModifiers; public ImmutableArray<ITypeSymbol> TypeArguments => _symbol.TypeArguments; public ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations => _symbol.TypeArgumentNullableAnnotations; public ImmutableArray<ITypeParameterSymbol> TypeParameters => _symbol.TypeParameters; public IMethodSymbol Construct(params ITypeSymbol[] typeArguments) => _symbol.Construct(typeArguments); public IMethodSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations) => _symbol.Construct(typeArguments, typeArgumentNullableAnnotations); public DllImportData GetDllImportData() => _symbol.GetDllImportData(); public IMethodSymbol ReduceExtensionMethod(ITypeSymbol receiverType) { // This implementation feels incorrect! return _symbol.ReduceExtensionMethod(receiverType); } public bool IsVararg => _symbol.IsVararg; public bool IsCheckedBuiltin => _symbol.IsCheckedBuiltin; public bool IsConditional => _symbol.IsConditional; public SignatureCallingConvention CallingConvention => _symbol.CallingConvention; public ImmutableArray<INamedTypeSymbol> UnmanagedCallingConventionTypes => _symbol.UnmanagedCallingConventionTypes; } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } private async Task<Project?> MapDocumentAsync(Document document, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); return project; } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { var project = await MapDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (project == null) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) return null; return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.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. using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } private async Task<Project?> MapDocumentAsync(Document document, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); return project; } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { var project = await MapDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (project == null) return null; var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) return null; return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.GetHashCode()))))); } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.PropertyAccessorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a getter for anonymous type property. /// </summary> private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { private readonly AnonymousTypePropertySymbol _property; internal AnonymousTypePropertyGetAccessorSymbol(AnonymousTypePropertySymbol property) // winmdobj output only effects setters, so we can always set this to false : base(property.ContainingType, SourcePropertyAccessorSymbol.GetAccessorName(property.Name, getNotSet: true, isWinMdOutput: false)) { _property = property; } public override MethodKind MethodKind { get { return MethodKind.PropertyGet; } } public override bool ReturnsVoid { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return _property.TypeWithAnnotations; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override Symbol AssociatedSymbol { get { return _property; } } public override ImmutableArray<Location> Locations { get { // The accessor for a anonymous type property has the same location as the property. return _property.Locations; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { // Do not call base.AddSynthesizedAttributes. // Dev11 does not emit DebuggerHiddenAttribute in property accessors } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents a getter for anonymous type property. /// </summary> private sealed partial class AnonymousTypePropertyGetAccessorSymbol : SynthesizedMethodBase { private readonly AnonymousTypePropertySymbol _property; internal AnonymousTypePropertyGetAccessorSymbol(AnonymousTypePropertySymbol property) // winmdobj output only effects setters, so we can always set this to false : base(property.ContainingType, SourcePropertyAccessorSymbol.GetAccessorName(property.Name, getNotSet: true, isWinMdOutput: false)) { _property = property; } public override MethodKind MethodKind { get { return MethodKind.PropertyGet; } } public override bool ReturnsVoid { get { return false; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return _property.TypeWithAnnotations; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override Symbol AssociatedSymbol { get { return _property; } } public override ImmutableArray<Location> Locations { get { // The accessor for a anonymous type property has the same location as the property. return _property.Locations; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { // Do not call base.AddSynthesizedAttributes. // Dev11 does not emit DebuggerHiddenAttribute in property accessors } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/Core/Def/Implementation/Snippets/IVsExpansionSessionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal static class IVsExpansionSessionExtensions { public static bool TryGetHeaderNode(this IVsExpansionSession expansionSession, string name, [NotNullWhen(true)] out IXMLDOMNode? node) { var query = name is null ? null : $@"node()[local-name()=""{name}""]"; IXMLDOMNode? localNode = null; if (!ErrorHandler.Succeeded(ErrorHandler.CallWithCOMConvention(() => expansionSession.GetHeaderNode(query, out localNode)))) { node = null; return false; } node = localNode; return node is not 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.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal static class IVsExpansionSessionExtensions { public static bool TryGetHeaderNode(this IVsExpansionSession expansionSession, string name, [NotNullWhen(true)] out IXMLDOMNode? node) { var query = name is null ? null : $@"node()[local-name()=""{name}""]"; IXMLDOMNode? localNode = null; if (!ErrorHandler.Succeeded(ErrorHandler.CallWithCOMConvention(() => expansionSession.GetHeaderNode(query, out localNode)))) { node = null; return false; } node = localNode; return node is not null; } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly IGlobalOptionService _globalOptions; private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IGlobalOptionService globalOptions, IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _globalOptions = globalOptions; _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // We check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var returnTextEdits = _globalOptions.GetOption(LspOptions.LspCompletionFeatureFlag) || _globalOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSInternalCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSInternalCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSInternalCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Adornments; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { /// <summary> /// Handle a completion request. /// </summary> internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?> { private readonly IGlobalOptionService _globalOptions; private readonly ImmutableHashSet<char> _csharpTriggerCharacters; private readonly ImmutableHashSet<char> _vbTriggerCharacters; private readonly CompletionListCache _completionListCache; public string Method => LSP.Methods.TextDocumentCompletionName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; public CompletionHandler( IGlobalOptionService globalOptions, IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders, CompletionListCache completionListCache) { _globalOptions = globalOptions; _csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany( lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet(); _completionListCache = completionListCache; } public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument; public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return null; } // C# and VB share the same LSP language server, and thus share the same default trigger characters. // We need to ensure the trigger character is valid in the document's language. For example, the '{' // character, while a trigger character in VB, is not a trigger character in C#. if (request.Context != null && request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter && !char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) && !char.IsLetterOrDigit(triggerCharacter) && !IsValidTriggerCharacterForDocument(document, triggerCharacter)) { return null; } var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false); var completionService = document.GetRequiredLanguageService<CompletionService>(); var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false); if (completionListResult == null) { return null; } var (list, isIncomplete, resultId) = completionListResult.Value; var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true; var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false; var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance); // Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size). // We check against the CompletionOption for test purposes only. Contract.ThrowIfNull(context.Solution); var returnTextEdits = _globalOptions.GetOption(LspOptions.LspCompletionFeatureFlag) || _globalOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language); TextSpan? defaultSpan = null; LSP.Range? defaultRange = null; if (returnTextEdits) { // We want to compute the document's text just once. documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // We use the first item in the completion list as our comparison point for span // and range for optimization when generating the TextEdits later on. var completionChange = await completionService.GetChangeAsync( document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false); // If possible, we want to compute the item's span and range just once. // Individual items can override this range later. defaultSpan = completionChange.TextChange.Span; defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText); } var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability(); var completionResolveData = new CompletionResolveData() { ResultId = resultId, }; var stringBuilder = new StringBuilder(); using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems); foreach (var item in list.Items) { var completionItemResolveData = supportsCompletionListData ? null : completionResolveData; var lspCompletionItem = await CreateLSPCompletionItemAsync( request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache, completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); lspCompletionItems.Add(lspCompletionItem); } var completionList = new LSP.VSInternalCompletionList { Items = lspCompletionItems.ToArray(), SuggestionMode = list.SuggestionModeItem != null, IsIncomplete = isIncomplete, }; if (supportsCompletionListData) { completionList.Data = completionResolveData; } if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability()) { PromoteCommonCommitCharactersOntoList(completionList); } var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList); return optimizedCompletionList; // Local functions bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter) { if (document.Project.Language == LanguageNames.CSharp) { return _csharpTriggerCharacters.Contains(triggerCharacter); } else if (document.Project.Language == LanguageNames.VisualBasic) { return _vbTriggerCharacters.Contains(triggerCharacter); } // Typescript still calls into this for completion. // Since we don't know what their trigger characters are, just return true. return true; } static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { if (supportsVSExtensions) { var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSInternalCompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId()); return vsCompletionItem; } else { var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>( request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache, completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); return roslynCompletionItem; } } static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>( LSP.CompletionParams request, Document document, CompletionItem item, CompletionResolveData? completionResolveData, bool supportsVSExtensions, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache, CompletionService completionService, string? clientName, bool returnTextEdits, bool snippetsSupported, StringBuilder stringBuilder, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new() { // Generate display text stringBuilder.Append(item.DisplayTextPrefix); stringBuilder.Append(item.DisplayText); stringBuilder.Append(item.DisplayTextSuffix); var completeDisplayText = stringBuilder.ToString(); stringBuilder.Clear(); var completionItem = new TCompletionItem { Label = completeDisplayText, SortText = item.SortText, FilterText = item.FilterText, Kind = GetCompletionKind(item.Tags), Data = completionResolveData, Preselect = ShouldItemBePreselected(item), }; // Complex text edits (e.g. override and partial method completions) are always populated in the // resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases. if (item.IsComplexTextEdit) { // Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet. // We can enable it for regular C# once LSP is used for local completion. if (snippetsSupported) { completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet; } } // If the feature flag is on, always return a TextEdit. else if (returnTextEdits) { var textEdit = await GenerateTextEdit( document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false); completionItem.TextEdit = textEdit; } // If the feature flag is off, return an InsertText. else { completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText; } var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions); if (commitCharacters != null) { completionItem.CommitCharacters = commitCharacters; } return completionItem; static async Task<LSP.TextEdit> GenerateTextEdit( Document document, CompletionItem item, CompletionService completionService, SourceText? documentText, TextSpan? defaultSpan, LSP.Range? defaultRange, CancellationToken cancellationToken) { Contract.ThrowIfNull(documentText); Contract.ThrowIfNull(defaultSpan); Contract.ThrowIfNull(defaultRange); var completionChange = await completionService.GetChangeAsync( document, item, cancellationToken: cancellationToken).ConfigureAwait(false); var completionChangeSpan = completionChange.TextChange.Span; var textEdit = new LSP.TextEdit() { NewText = completionChange.TextChange.NewText ?? "", Range = completionChangeSpan == defaultSpan.Value ? defaultRange : ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText), }; return textEdit; } } static string[]? GetCommitCharacters( CompletionItem item, Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache, bool supportsVSExtensions) { // VSCode does not have the concept of soft selection, the list is always hard selected. // In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc // we create a completion item without any specific commit characters. This means only tab / enter will commit. // VS supports soft selection, so we only do this for non-VS clients. if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection) { return Array.Empty<string>(); } var commitCharacterRules = item.Rules.CommitCharacterRules; // VS will use the default commit characters if no items are specified on the completion item. // However, other clients like VSCode do not support this behavior so we must specify // commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987 if (supportsVSExtensions && commitCharacterRules.IsEmpty) { return null; } if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters)) { return cachedCommitCharacters; } using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters); commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters); foreach (var rule in commitCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: commitCharacters.UnionWith(rule.Characters); continue; case CharacterSetModificationKind.Remove: commitCharacters.ExceptWith(rule.Characters); continue; case CharacterSetModificationKind.Replace: commitCharacters.Clear(); commitCharacters.AddRange(rule.Characters); break; } } var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray(); currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters); return lspCommitCharacters; } static void PromoteCommonCommitCharactersOntoList(LSP.VSInternalCompletionList completionList) { var defaultCommitCharacters = CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray(); var commitCharacterReferences = new Dictionary<object, int>(); var mostUsedCount = 0; string[]? mostUsedCommitCharacters = null; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; var commitCharacters = completionItem.CommitCharacters; if (commitCharacters == null) { // The commit characters on the item are null, this means the commit characters are actually // the default commit characters we passed in the initialize request. commitCharacters = defaultCommitCharacters; } commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount); existingCount++; if (existingCount > mostUsedCount) { // Capture the most used commit character counts so we don't need to re-iterate the array later mostUsedCommitCharacters = commitCharacters; mostUsedCount = existingCount; } commitCharacterReferences[commitCharacters] = existingCount; } Contract.ThrowIfNull(mostUsedCommitCharacters); // Promoted the most used commit characters onto the list and then remove these from child items. completionList.CommitCharacters = mostUsedCommitCharacters; for (var i = 0; i < completionList.Items.Length; i++) { var completionItem = completionList.Items[i]; if (completionItem.CommitCharacters == mostUsedCommitCharacters) { completionItem.CommitCharacters = null; } } } } private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync( LSP.CompletionParams request, SourceText sourceText, Document document, OptionSet completionOptions, CompletionService completionService, CancellationToken cancellationToken) { var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position); var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false); var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions; (CompletionList List, long ResultId)? result; if (isTriggerForIncompleteCompletions) { // We don't have access to the original trigger, but we know the completion list is already present. // It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger. var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke); result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } else { // This is a new completion request, clear out the last result Id for incomplete results. result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false); } if (result == null) { return null; } var resultId = result.Value.ResultId; var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize); var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document); return (completionList, isIncomplete, resultId); } private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync( LSP.CompletionParams request, Document document, int position, CompletionTrigger completionTrigger, OptionSet completionOptions, CompletionService completionService, CompletionListCache completionListCache, CancellationToken cancellationToken) { var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (completionList == null || completionList.Items.IsEmpty) { return null; } // Cache the completion list so we can avoid recomputation in the resolve handler var resultId = completionListCache.UpdateCache(request.TextDocument, completionList); return (completionList, resultId); } private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList( CompletionList completionList, int completionListMaxSize, TextSpan completionListSpan, CompletionTrigger completionTrigger, SourceText sourceText, Document document) { var filterText = sourceText.GetSubText(completionListSpan).ToString(); // Use pattern matching to determine which items are most relevant out of the calculated items. using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder); var index = 0; var completionHelper = CompletionHelper.GetHelper(document); foreach (var item in completionList.Items) { if (CompletionHelper.TryCreateMatchResult<CompletionItem?>( completionHelper, item, editorCompletionItem: null, filterText, completionTrigger.Kind, GetFilterReason(completionTrigger), recentItems: ImmutableArray<string>.Empty, includeMatchSpans: false, index, out var matchResult)) { matchResultsBuilder.Add(matchResult); index++; } } // Next, we sort the list based on the pattern matching result. matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer); // Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000. var filteredList = matchResultsBuilder .Take(completionListMaxSize) .Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem))) .Select(matchResult => matchResult.RoslynCompletionItem) .ToImmutableArray(); var newCompletionList = completionList.WithItems(filteredList); // Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will // not generate any more completion items. This means that we should be checking if the matchedResults is larger // than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion // when a character is deleted to go from a complete list back to an incomplete list. // For example, the following scenario. // User types "So" -> server gives subset of items for "So" with isIncomplete = true // User types "m" -> server gives entire set of items for "Som" with isIncomplete = false // User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n" // // Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som" // so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large. // VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142 var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length; return (newCompletionList, isIncomplete); static CompletionFilterReason GetFilterReason(CompletionTrigger trigger) { return trigger.Kind switch { CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion, CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion, _ => CompletionFilterReason.Other, }; } } private static bool ShouldItemBePreselected(CompletionItem completionItem) { // An item should be preselcted for LSP when the match priority is preselect and the item is hard selected. // LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing. return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection; } internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider) { if (provider is LSPCompletionProvider lspProvider) { return lspProvider.TriggerCharacters; } return ImmutableHashSet<char>.Empty; } internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken) { // Filter out snippets as they are not supported in the LSP client // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740 // Filter out unimported types for now as there are two issues with providing them: // 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace. // https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759 // 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request. // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/ // 3. LSP client should support completion filters / expanders var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var completionOptions = documentOptions .WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude) .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false) .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false); return completionOptions; } private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags) { foreach (var tag in tags) { if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind)) { return completionItemKind; } } return LSP.CompletionItemKind.Text; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly CompletionHandler _completionHandler; public TestAccessor(CompletionHandler completionHandler) => _completionHandler = completionHandler; public CompletionListCache GetCache() => _completionHandler._completionListCache; } private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>> { public static readonly CommitCharacterArrayComparer Instance = new(); private CommitCharacterArrayComparer() { } public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y) { for (var i = 0; i < x.Length; i++) { var xKind = x[i].Kind; var yKind = y[i].Kind; if (xKind != yKind) { return false; } var xCharacters = x[i].Characters; var yCharacters = y[i].Characters; if (xCharacters.Length != yCharacters.Length) { return false; } for (var j = 0; j < xCharacters.Length; j++) { if (xCharacters[j] != yCharacters[j]) { return false; } } } return true; } public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj) { var combinedHash = Hash.CombineValues(obj); return combinedHash; } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/Xaml/Impl/Telemetry/IXamlLanguageServerFeedbackService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry { /// <summary> /// Service that collects data for Telemetry in XamlLanguageServer /// </summary> internal interface IXamlLanguageServerFeedbackService { /// <summary> /// Create a RequestScope of a request of given documentId /// </summary> IRequestScope CreateRequestScope(DocumentId? documentId, string methodName); } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry { /// <summary> /// Service that collects data for Telemetry in XamlLanguageServer /// </summary> internal interface IXamlLanguageServerFeedbackService { /// <summary> /// Create a RequestScope of a request of given documentId /// </summary> IRequestScope CreateRequestScope(DocumentId? documentId, string methodName); } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/ExpressionEvaluator/Core/Test/FunctionResolver/CSharpFunctionResolverTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public class CSharpFunctionResolverTests : FunctionResolverTestBase { [Fact] public void OnLoad() { var source = @"class C { static void F(object o) { } object F() => null; }"; var compilation = CreateCompilation(source); var module = new Module(compilation.EmitToArray()); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var request = new Request(null, MemberSignatureParser.Parse("C.F")); resolver.EnableResolution(process, request); VerifySignatures(request); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(request, "C.F(System.Object)", "C.F()"); } } /// <summary> /// ShouldEnableFunctionResolver should not be called /// until the first module is available for binding. /// </summary> [Fact] public void ShouldEnableFunctionResolver() { var sourceA = @"class A { static void F() { } static void G() { } }"; var sourceB = @"class B { static void F() { } static void G() { } }"; var bytesA = CreateCompilation(sourceA).EmitToArray(); var bytesB = CreateCompilation(sourceB).EmitToArray(); var resolver = Resolver.CSharpResolver; // Two modules loaded before two global requests, // ... resolver enabled. var moduleA = new Module(bytesA, name: "A.dll"); var moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded before two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "B.F()"); VerifySignatures(requestG, "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded after two global requests, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules after two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } } /// <summary> /// Should only handle requests with expected language id or /// default language id or causality breakpoints. /// </summary> [WorkItem(15119, "https://github.com/dotnet/roslyn/issues/15119")] [Fact] public void LanguageId() { var source = @"class C { static void F() { } }"; var bytes = CreateCompilation(source).EmitToArray(); var resolver = Resolver.CSharpResolver; var unknownId = Guid.Parse("F02FB87B-64EC-486E-B039-D4A97F48858C"); var csharpLanguageId = Guid.Parse("3f5162f8-07c6-11d3-9053-00c04fa302a1"); var vbLanguageId = Guid.Parse("3a12d0b8-c26c-11d0-b442-00a0244a1dd2"); var cppLanguageId = Guid.Parse("3a12d0b7-c26c-11d0-b442-00a0244a1dd2"); // Module loaded before requests. var module = new Module(bytes); using (var process = new Process(module)) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestDefaultId); VerifySignatures(requestDefaultId, "C.F()"); resolver.EnableResolution(process, requestUnknown); VerifySignatures(requestUnknown); resolver.EnableResolution(process, requestCausalityBreakpoint); VerifySignatures(requestCausalityBreakpoint, "C.F()"); resolver.EnableResolution(process, requestMethodId); VerifySignatures(requestMethodId); resolver.EnableResolution(process, requestCSharp); VerifySignatures(requestCSharp, "C.F()"); resolver.EnableResolution(process, requestVB); VerifySignatures(requestVB); resolver.EnableResolution(process, requestCPP); VerifySignatures(requestCPP); } // Module loaded after requests. module = new Module(bytes); using (var process = new Process()) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestCPP); resolver.EnableResolution(process, requestVB); resolver.EnableResolution(process, requestCSharp); resolver.EnableResolution(process, requestMethodId); resolver.EnableResolution(process, requestCausalityBreakpoint); resolver.EnableResolution(process, requestUnknown); resolver.EnableResolution(process, requestDefaultId); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(requestDefaultId, "C.F()"); VerifySignatures(requestUnknown); VerifySignatures(requestCausalityBreakpoint, "C.F()"); VerifySignatures(requestMethodId); VerifySignatures(requestCSharp, "C.F()"); VerifySignatures(requestVB); VerifySignatures(requestCPP); } } [Fact] public void MissingMetadata() { var sourceA = @"class A { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var sourceC = @"class C { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var moduleA = new Module(CreateCompilation(sourceA).EmitToArray(), name: "A.dll"); var moduleB = new Module(default(ImmutableArray<byte>), name: "B.dll"); var moduleC = new Module(CreateCompilation(sourceC).EmitToArray(), name: "C.dll"); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var requestAll = new Request(null, MemberSignatureParser.Parse("F1")); var requestA = new Request("A.dll", MemberSignatureParser.Parse("F2")); var requestB = new Request("B.dll", MemberSignatureParser.Parse("F3")); var requestC = new Request("C.dll", MemberSignatureParser.Parse("F4")); // Request to all modules. resolver.EnableResolution(process, requestAll); Assert.Equal(0, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); // Load module A (available). process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module B (missing). process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module C (available). process.AddModule(moduleC); resolver.OnModuleLoad(process, moduleC); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module A (available). resolver.EnableResolution(process, requestA); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module B (missing). resolver.EnableResolution(process, requestB); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module C (available). resolver.EnableResolution(process, requestC); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(2, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC, "C.F4()"); } } [Fact] public void ModuleName() { var sourceA = @"public struct A { static void F() { } }"; var nameA = GetUniqueName(); var compilationA = CreateCompilation(sourceA, assemblyName: nameA); var imageA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(imageA).GetReference(); var sourceB = @"class B { static void F(A a) { } static void Main() { } }"; var nameB = GetUniqueName(); var compilationB = CreateCompilation(sourceB, assemblyName: nameB, options: TestOptions.DebugExe, references: new[] { refA }); var imageB = compilationB.EmitToArray(); using (var process = new Process(new Module(imageA, nameA + ".dll"), new Module(imageB, nameB + ".exe"))) { var signature = MemberSignatureParser.Parse("F"); var resolver = Resolver.CSharpResolver; // No module name. var request = new Request("", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()", "B.F(A)"); // DLL module name, uppercase. request = new Request(nameA.ToUpper() + ".DLL", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()"); // EXE module name. request = new Request(nameB + ".EXE", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, lowercase. request = new Request(nameB.ToLower() + ".exe", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, no extension. request = new Request(nameB, signature); resolver.EnableResolution(process, request); VerifySignatures(request); } } [Fact] [WorkItem(55475, "https://github.com/dotnet/roslyn/issues/55475")] public void BadMetadata() { var source = "class A { static void F() {} }"; var compilation = CreateCompilation(source); using var process = new Process( new Module(compilation.EmitToArray()), new Module(metadata: default), // emulates failure of the debugger to retrieve metadata new Module(metadata: TestResources.MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.ToImmutableArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.F()"); } [Fact] public void Arrays() { var source = @"class A { } class B { static void F(A o) { } static void F(A[] o) { } static void F(A[,,] o) { } static void F(A[,,][] o) { } static void F(A[][,,] o) { } static void F(A[][][] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(A)", "B.F(A[])", "B.F(A[,,])", "B.F(A[][,,])", "B.F(A[,,][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A)", "B.F(A)"); Resolve(process, resolver, "F(A[])", "B.F(A[])"); Resolve(process, resolver, "F(A[][])"); Resolve(process, resolver, "F(A[,])"); Resolve(process, resolver, "F(A[,,])", "B.F(A[,,])"); Resolve(process, resolver, "F(A[,,][])", "B.F(A[,,][])"); Resolve(process, resolver, "F(A[][,,])", "B.F(A[][,,])"); Resolve(process, resolver, "F(A[,][,,])"); Resolve(process, resolver, "F(A[][][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A[][][][])"); } } [Fact] public void Pointers() { var source = @"class C { static unsafe void F(int*[] p) { } static unsafe void F(int** q) { } }"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Int32*[])", "C.F(System.Int32**)"); Resolve(process, resolver, "F(int)"); Resolve(process, resolver, "F(int*)"); Resolve(process, resolver, "F(int[])"); Resolve(process, resolver, "F(int*[])", "C.F(System.Int32*[])"); Resolve(process, resolver, "F(int**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(Int32**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(C<int*>)"); Resolve(process, resolver, "F(C<int>*)"); } } [Fact] public void Nullable() { var source = @"struct S { void F(S? o) { } static void F(int?[] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "S.F(System.Nullable<S>)", "S.F(System.Nullable<System.Int32>[])"); Resolve(process, resolver, "F(S)"); Resolve(process, resolver, "F(S?)", "S.F(System.Nullable<S>)"); Resolve(process, resolver, "F(S??)"); Resolve(process, resolver, "F(int?[])", "S.F(System.Nullable<System.Int32>[])"); } } [Fact] public void ByRef() { var source = @"class @ref { } class @out { } class C { static void F(@out a, @ref b) { } static void F(ref @out a, out @ref b) { b = null; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(out, ref)", "C.F(ref out, ref ref)"); Assert.Null(MemberSignatureParser.Parse("F(ref, out)")); Assert.Null(MemberSignatureParser.Parse("F(ref ref, out out)")); Resolve(process, resolver, "F(@out, @ref)", "C.F(out, ref)"); Resolve(process, resolver, "F(@out, out @ref)"); Resolve(process, resolver, "F(ref @out, @ref)"); Resolve(process, resolver, "F(ref @out, out @ref)", "C.F(ref out, ref ref)"); Resolve(process, resolver, "F(out @out, ref @ref)", "C.F(ref out, ref ref)"); } } [Fact] public void Methods() { var source = @"abstract class A { abstract internal object F(); } class B { object F() => null; } class C { static object F() => null; } interface I { object F(); }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "C.F()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "B.F", "B.F()"); Resolve(process, resolver, "B.F()", "B.F()"); Resolve(process, resolver, "B.F(object)"); Resolve(process, resolver, "B.F<T>"); Resolve(process, resolver, "C.F", "C.F()"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Methods_ExplicitInterfaceImplementation() { var source = @" interface I { void F(); } interface J { void F(); } class C : I, J { class I { void F() { } } void global::I.F() { } void J.F() { } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F", "C.global::I.F()", "C.J.F()"); // resolves to the nested class members: Resolve(process, resolver, "C.I.F", "C.I.F()"); // does not resolve Resolve(process, resolver, "C.J.F"); } [Fact] public void Properties() { var source = @"abstract class A { abstract internal object P { get; set; } } class B { object P { get; set; } } class C { static object P { get; } } class D { int P { set { } } } interface I { object P { get; set; } }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "P", "B.get_P()", "B.set_P(System.Object)", "C.get_P()", "D.set_P(System.Int32)"); Resolve(process, resolver, "A.P"); Resolve(process, resolver, "B.P", "B.get_P()", "B.set_P(System.Object)"); Resolve(process, resolver, "B.P()"); Resolve(process, resolver, "B.P(object)"); Resolve(process, resolver, "B.P<T>"); Resolve(process, resolver, "C.P", "C.get_P()"); Resolve(process, resolver, "C.P()"); Resolve(process, resolver, "D.P", "D.set_P(System.Int32)"); Resolve(process, resolver, "D.P()"); Resolve(process, resolver, "D.P(object)"); Resolve(process, resolver, "get_P", "B.get_P()", "C.get_P()"); Resolve(process, resolver, "set_P", "B.set_P(System.Object)", "D.set_P(System.Int32)"); Resolve(process, resolver, "B.get_P()", "B.get_P()"); Resolve(process, resolver, "B.set_P", "B.set_P(System.Object)"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Properties_ExplicitInterfaceImplementation() { var source = @" interface I { int P { get; set; } } interface J { int P { get; set; } } class C : I, J { class I { int P { get; set; } } int global::I.P { get; set; } int J.P { get; set; } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.P", "C.global::I.get_P()", "C.global::I.set_P(System.Int32)", "C.J.get_P()", "C.J.set_P(System.Int32)"); Resolve(process, resolver, "C.get_P", "C.global::I.get_P()", "C.J.get_P()"); Resolve(process, resolver, "C.set_P", "C.global::I.set_P(System.Int32)", "C.J.set_P(System.Int32)"); // resolves to the nested class members: Resolve(process, resolver, "C.I.P", "C.I.get_P()", "C.I.set_P(System.Int32)"); Resolve(process, resolver, "C.I.get_P", "C.I.get_P()"); Resolve(process, resolver, "C.I.set_P", "C.I.set_P(System.Int32)"); // does not resolve Resolve(process, resolver, "C.J.P"); Resolve(process, resolver, "C.J.get_P"); Resolve(process, resolver, "C.J.set_P"); } [Fact] public void Events() { var source = @" abstract class A { abstract internal event System.Action E; } class B { event System.Action E; } class C { static event System.Action E; } class D { event System.Action E { add {} remove {} } } interface I { event System.Action E; }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "E", "B.add_E(System.Action)", "B.remove_E(System.Action)", "C.add_E(System.Action)", "C.remove_E(System.Action)", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "A.E"); Resolve(process, resolver, "B.E", "B.add_E(System.Action)", "B.remove_E(System.Action)"); Resolve(process, resolver, "B.E()"); Resolve(process, resolver, "B.E(System.Action)", "B.add_E(System.Action)", "B.remove_E(System.Action)"); Resolve(process, resolver, "B.E<T>"); Resolve(process, resolver, "C.E", "C.add_E(System.Action)", "C.remove_E(System.Action)"); Resolve(process, resolver, "C.E(System.Action)", "C.add_E(System.Action)", "C.remove_E(System.Action)"); Resolve(process, resolver, "D.E", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "D.E()"); Resolve(process, resolver, "D.E(System.Action)", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "add_E", "B.add_E(System.Action)", "C.add_E(System.Action)", "D.add_E(System.Action)"); Resolve(process, resolver, "remove_E", "B.remove_E(System.Action)", "C.remove_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "B.add_E(System.Action)", "B.add_E(System.Action)"); Resolve(process, resolver, "B.remove_E", "B.remove_E(System.Action)"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Events_ExplicitInterfaceImplementation() { var source = @" interface I { event System.Action E; } interface J { event System.Action E; } class C : I, J { class I { event System.Action E { add {} remove {} } } event System.Action global::I.E { add {} remove {} } event System.Action J.E { add {} remove {} } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.E", "C.global::I.add_E(System.Action)", "C.global::I.remove_E(System.Action)", "C.J.add_E(System.Action)", "C.J.remove_E(System.Action)"); Resolve(process, resolver, "C.add_E", "C.global::I.add_E(System.Action)", "C.J.add_E(System.Action)"); Resolve(process, resolver, "C.remove_E", "C.global::I.remove_E(System.Action)", "C.J.remove_E(System.Action)"); // resolves to the nested class members: Resolve(process, resolver, "C.I.E", "C.I.add_E(System.Action)", "C.I.remove_E(System.Action)"); Resolve(process, resolver, "C.I.add_E", "C.I.add_E(System.Action)"); Resolve(process, resolver, "C.I.remove_E", "C.I.remove_E(System.Action)"); // does not resolve Resolve(process, resolver, "C.J.E"); Resolve(process, resolver, "C.J.add_E"); Resolve(process, resolver, "C.J.remove_E"); } [Fact] public void Constructors() { var source = @"class A { static A() { } A() { } A(object o) { } } class B { } class C<T> { } class D { static object A => null; static void B<T>() { } } class E { static int x = 1; } "; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A", "A..cctor()", "A..ctor()", "A..ctor(System.Object)", "D.get_A()"); Resolve(process, resolver, "A.A", "A..cctor()", "A..ctor()", "A..ctor(System.Object)"); Resolve(process, resolver, "B", "B..ctor()"); Resolve(process, resolver, "B<T>", "D.B<T>()"); Resolve(process, resolver, "C", "C<T>..ctor()"); Resolve(process, resolver, "C<T>"); Resolve(process, resolver, "C<T>.C", "C<T>..ctor()"); Resolve(process, resolver, "E", "E..ctor()", "E..cctor()"); Assert.Null(MemberSignatureParser.Parse(".ctor")); Assert.Null(MemberSignatureParser.Parse("A..ctor")); } } [Fact] public void GenericMethods() { var source = @"class A { static void F() { } void F<T, U>() { } static void F<T>() { } } class A<T> { static void F() { } void F<U, V>() { } } class B : A<int> { static void F<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // Note, Dev14 matches type ignoring type parameters. For instance, // "A<T>.F" will bind to A.F() and A<T>.F(), and "A.F" will bind to A.F() // and A<T>.F. However, Dev14 does expect method type parameters to // match. Here, we expect both type and method parameters to match. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A.F", "A.F()"); Resolve(process, resolver, "A.F<U>()", "A.F<T>()"); Resolve(process, resolver, "A.F<T>", "A.F<T>()"); Resolve(process, resolver, "A.F<T, T>", "A.F<T, U>()"); Assert.Null(MemberSignatureParser.Parse("A.F<>()")); Assert.Null(MemberSignatureParser.Parse("A.F<,>()")); Resolve(process, resolver, "A<T>.F", "A<T>.F()"); Resolve(process, resolver, "A<_>.F<_>"); Resolve(process, resolver, "A<_>.F<_, _>", "A<T>.F<U, V>()"); Resolve(process, resolver, "B.F()"); Resolve(process, resolver, "B.F<T>()", "B.F<T>()"); Resolve(process, resolver, "B.F<T, U>()"); } } [Fact] public void Namespaces() { var source = @"namespace N { namespace M { class A<T> { static void F() { } } } } namespace N { class B { static void F() { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "N.B.F()", "N.M.A<T>.F()"); Resolve(process, resolver, "A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.A<T>.F"); Resolve(process, resolver, "M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.B.F", "N.B.F()"); } } [Fact] public void NestedTypes() { var source = @"class A { class B { static void F() { } } class B<T> { static void F<U>() { } } } class B { static void F() { } } namespace N { class A<T> { class B { static void F<U>() { } } class B<U> { static void F() { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // See comment in GenericMethods regarding differences with Dev14. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "A.B.F()", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "F<T>", "A.B<T>.F<U>()", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "A.B.F", "A.B.F()"); Resolve(process, resolver, "A.B.F<T>"); Resolve(process, resolver, "A.B<T>.F<U>", "A.B<T>.F<U>()"); Resolve(process, resolver, "A<T>.B.F<U>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A<T>.B<U>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B.F", "B.F()", "A.B.F()"); Resolve(process, resolver, "B.F<T>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "B<T>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>()"); Assert.Null(MemberSignatureParser.Parse("A+B.F")); Assert.Null(MemberSignatureParser.Parse("A.B`1.F<T>")); } } [Fact] public void NamespacesAndTypes() { var source = @"namespace A.B { class T { } class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } namespace A { class B<T> { internal class C { static void F(C c) { } static void F(A.B.C c) { } } } } class A<T> { internal class B { internal class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "F(C)", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B.C)", "A.B.C.F(A.B.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B<T>.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A.B.C.F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A<T>.B.C.F", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "A.B<T>.C.F", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "B<T>.C.F(B<T>.C)", "A.B<T>.C.F(A.B<T>.C)"); } } [Fact] public void NamespacesAndTypes_More() { var source = @"namespace A1.B { class C { static void F(C c) { } } } namespace A2 { class B { internal class C { static void F(C c) { } static void F(A1.B.C c) { } } } } class A3 { internal class B { internal class C { static void F(C c) { } static void F(A2.B.C c) { } } } } namespace B { class C { static void F(C c) { } static void F(A3.B.C c) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(B.C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A1.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A1.B.C)"); Resolve(process, resolver, "B.C.F(A2.B.C)", "A2.B.C.F(A2.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A3.B.C)", "B.C.F(A3.B.C)", "A3.B.C.F(A3.B.C)"); } } [Fact] public void TypeParameters() { var source = @"class A { class B<T> { static void F<U>(B<T> t) { } static void F<U>(B<U> u) { } } } class A<T> { class B<U> { static void F<V>(T t) { } static void F<V>(A<U> u) { } static void F<V>(B<V> v) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "F<T>(B<T>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "F<U>(B<T>)"); // No T in signature to bind to. Resolve(process, resolver, "F<T>(B<U>)"); // No U in signature to bind to. Resolve(process, resolver, "B<X>.F<Y>(B<X>)", "A.B<T>.F<U>(A.B<T>)"); Resolve(process, resolver, "B<X>.F<Y>(B<Y>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<U>.F<V>(T)"); // No T in signature to bind to. Resolve(process, resolver, "B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<U>)"); Resolve(process, resolver, "B<U>.F<V>(B<V>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<V>.F<U>(B<U>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(X)", "A<T>.B<U>.F<V>(T)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(B<Z>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); } } [Fact] public void DifferentCase_MethodsAndProperties() { var source = @"class A { static void method() { } static void Method(object o) { } object property => null; } class B { static void Method() { } object Property { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "method", "A.method()"); Resolve(process, resolver, "Method", "A.Method(System.Object)", "B.Method()"); Resolve(process, resolver, "property", "A.get_property()"); Resolve(process, resolver, "Property", "B.get_Property()", "B.set_Property(System.Object)"); Resolve(process, resolver, "PROPERTY"); Resolve(process, resolver, "get_property", "A.get_property()"); Resolve(process, resolver, "GET_PROPERTY"); } } [Fact] public void DifferentCase_NamespacesAndTypes() { var source = @"namespace one.two { class THREE { static void Method(THREE t) { } } } namespace One.Two { class Three { static void Method(Three t) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "Method", "One.Two.Three.Method(One.Two.Three)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "three.Method"); Resolve(process, resolver, "Method(three)"); Resolve(process, resolver, "THREE.Method(THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "One.Two.Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "ONE.TWO.THREE.Method"); Resolve(process, resolver, "Method(One.Two.Three)", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "Method(one.two.THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Method(one.two.Three)"); Resolve(process, resolver, "THREE", "one.two.THREE..ctor()"); } } [Fact] public void TypeReferences() { var sourceA = @"public class A<T> { public class B<U> { static void F<V, W>() { } } } namespace N { public class C<T> { } }"; var compilationA = CreateCompilation(sourceA); var bytesA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var sourceB = @"class D<T> { static void F<U, V>(N.C<A<U>.B<V>[]> b) { } }"; var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesA), new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T, U>", "A<T>.B<U>.F<V, W>()", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(C)"); // No type argument for C<> Resolve(process, resolver, "F<T, U>(C<T>)"); // Incorrect type argument for C<> Resolve(process, resolver, "F<T, U>(C<B<U>>)"); // No array qualifier Resolve(process, resolver, "F<T, U>(C<B<T>[]>)"); // Incorrect type argument for B<> Resolve(process, resolver, "F<T, U>(C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(N.C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>[]>)"); // No nested type B Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Z>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Y>[]>)"); // Incorrect type argument for B<>. } } [Fact] public void Keywords_MethodName() { var source = @"namespace @namespace { struct @struct { object @public => 1; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("public")); Assert.Null(MemberSignatureParser.Parse("namespace.@struct.@public")); Assert.Null(MemberSignatureParser.Parse("@namespace.struct.@public")); Assert.Null(MemberSignatureParser.Parse("@[email protected]")); Resolve(process, resolver, "@public", "namespace.struct.get_public()"); Resolve(process, resolver, "@namespace.@struct.@public", "namespace.struct.get_public()"); } } [Fact] public void Keywords_MethodTypeParameter() { var source = @"class @class<@in> { static void F<@out>(@in i, @out o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F<out>")); Assert.Null(MemberSignatureParser.Parse("F<in>")); Assert.Null(MemberSignatureParser.Parse("class<@in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<@in>.F<out>")); Resolve(process, resolver, "F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "F<@in>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@in>.F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@this>.F<@base>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<T>.F<U>", "class<in>.F<out>(in, out)"); } } [Fact] public void Keywords_ParameterName() { var source = @"namespace @namespace { struct @struct { } } class C { static void F(@namespace.@struct s) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(struct)")); Assert.Null(MemberSignatureParser.Parse("F(namespace.@struct)")); Resolve(process, resolver, "F(@struct)", "C.F(namespace.struct)"); Resolve(process, resolver, "F(@namespace.@struct)", "C.F(namespace.struct)"); } } [Fact] public void Keywords_ParameterTypeArgument() { var source = @"class @this { internal class @base { } } class @class<T> { } class C { static void F(@class<@this.@base> c) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(@class<base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<this.@base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<@this.base>)")); Resolve(process, resolver, "F(@class<@base>)", "C.F(class<this.base>)"); Resolve(process, resolver, "F(@class<@this.@base>)", "C.F(class<this.base>)"); } } [Fact] public void EscapedNames() { var source = @"class @object { } class Object { } class C { static void F(@object o) { } static void F(Object o) { } static void F(object o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(Object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(System.Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(@object)", "C.F(object)"); Resolve(process, resolver, "F(@Object)", "C.F(Object)", "C.F(System.Object)"); } } [Fact] public void SpecialTypes() { var source = @"class C<T1, T2, T3, T4> { } class C { static void F(bool a, char b, sbyte c, byte d) { } static void F(short a, ushort b, int c, uint d) { } static void F(C<uint, long, ulong, float> o) { } static void F(C<double, string, object, decimal> o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(bool, char, sbyte, byte)", "C.F(System.Boolean, System.Char, System.SByte, System.Byte)"); Resolve(process, resolver, "F(System.Int16, System.UInt16, System.Int32, System.UInt32)", "C.F(System.Int16, System.UInt16, System.Int32, System.UInt32)"); Resolve(process, resolver, "F(C<UInt32, Int64, UInt64, Single>)", "C.F(C<System.UInt32, System.Int64, System.UInt64, System.Single>)"); Resolve(process, resolver, "F(C<double, string, object, decimal>)", "C.F(C<System.Double, System.String, System.Object, System.Decimal>)"); Resolve(process, resolver, "F(bool, char, sbyte)"); Resolve(process, resolver, "F(C<double, string, object, decimal, bool>)"); } } [Fact] public void SpecialTypes_More() { var source = @"class C { static void F(System.IntPtr p) { } static void F(System.UIntPtr p) { } static void F(System.TypedReference r) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(object)"); Resolve(process, resolver, "F(IntPtr)", "C.F(System.IntPtr)"); Resolve(process, resolver, "F(UIntPtr)", "C.F(System.UIntPtr)"); Resolve(process, resolver, "F(TypedReference)", "C.F(System.TypedReference)"); } } // Binding to "dynamic" type refs is not supported. // This is consistent with Dev14. [Fact] public void Dynamic() { var source = @"class C<T> { } class C { static void F(dynamic d) { } static void F(C<dynamic[]> d) { } }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Object)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(C<object[]>)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(dynamic)"); Resolve(process, resolver, "F(C<dynamic[]>)"); } } [Fact] public void Iterator() { var source = @"class C { static System.Collections.IEnumerable F() { yield break; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] public void Async() { var source = @"using System.Threading.Tasks; class C { static async Task F() { await Task.Delay(0); } }"; var compilation = CreateCompilationWithMscorlib46(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] [WorkItem(55242, "https://github.com/dotnet/roslyn/issues/55242")] public void LocalFunctions() { var source = @" void F() { void G() { } } class F { void G() { void G() { } } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "G", "Program.<<Main>$>g__G|0_1()", "F.G()", "F.<G>g__G|0_0()"); Resolve(process, resolver, "Program.G", "Program.<<Main>$>g__G|0_1()"); Resolve(process, resolver, "F.G", "F.G()", "F.<G>g__G|0_0()"); Resolve(process, resolver, "F.G.G"); } [Fact(Skip = "global:: not supported")] public void Global() { var source = @"class C { static void F(N.C o) { } static void F(global::C o) { } } namespace N { class C { static void F(N.C o) { } static void F(global::C o) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F(C)", "C.F(N.C)", "C.F(C)", "N.C.F(N.C)", "N.C.F(C)"); Resolve(process, resolver, "C.F(N.C)", "C.F(N.C)", "N.C.F(N.C)"); Resolve(process, resolver, "global::C.F(C)", "C.F(N.C)", "C.F(C)"); // Dev14 does not bind global:: Resolve(process, resolver, "C.F(global::C)", "C.F(C)", "N.C.F(C)"); // Dev14 does not bind global:: } } // Since MetadataDecoder does not load referenced // assemblies, the arity or a type reference is determined // by the type name: e.g.: "C`2". If the arity from the name is // different from the number of generic type arguments, the // method signature containing the type reference is ignored. [Fact] public void UnexpectedArity() { var sourceA = @".class public A<T> { }"; var sourceB = @"class B { static void F(object o) { } static void F(A<object> a) { } }"; ImmutableArray<byte> bytesA; ImmutableArray<byte> pdbA; EmitILToArray(sourceA, appendDefaultHeader: true, includePdb: false, assemblyBytes: out bytesA, pdbBytes: out pdbA); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(System.Object)", "B.F([notsupported])"); Resolve(process, resolver, "F(A<object>)"); } } /// <summary> /// Should not resolve to P/Invoke methods. /// </summary> [Fact] public void PInvoke() { var source = @"using System.Runtime.InteropServices; class A { [DllImport(""extern.dll"")] public static extern int F(); } class B { public static int F() => 0; }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()"); } } private static void Resolve(Process process, Resolver resolver, string str, params string[] expectedSignatures) { var signature = MemberSignatureParser.Parse(str); Assert.NotNull(signature); Resolve(process, resolver, signature, expectedSignatures); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { public class CSharpFunctionResolverTests : FunctionResolverTestBase { [Fact] public void OnLoad() { var source = @"class C { static void F(object o) { } object F() => null; }"; var compilation = CreateCompilation(source); var module = new Module(compilation.EmitToArray()); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var request = new Request(null, MemberSignatureParser.Parse("C.F")); resolver.EnableResolution(process, request); VerifySignatures(request); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(request, "C.F(System.Object)", "C.F()"); } } /// <summary> /// ShouldEnableFunctionResolver should not be called /// until the first module is available for binding. /// </summary> [Fact] public void ShouldEnableFunctionResolver() { var sourceA = @"class A { static void F() { } static void G() { } }"; var sourceB = @"class B { static void F() { } static void G() { } }"; var bytesA = CreateCompilation(sourceA).EmitToArray(); var bytesB = CreateCompilation(sourceB).EmitToArray(); var resolver = Resolver.CSharpResolver; // Two modules loaded before two global requests, // ... resolver enabled. var moduleA = new Module(bytesA, name: "A.dll"); var moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded before two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "B.F()"); VerifySignatures(requestG, "B.G()"); } // ... resolver disabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false, modules: new[] { moduleA, moduleB })) { var requestF = new Request("B.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("B.dll", MemberSignatureParser.Parse("G")); Assert.Equal(0, process.ShouldEnableRequests); resolver.EnableResolution(process, requestF); Assert.Equal(1, process.ShouldEnableRequests); resolver.EnableResolution(process, requestG); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules loaded after two global requests, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()", "B.F()"); VerifySignatures(requestG, "A.G()", "B.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request(null, MemberSignatureParser.Parse("F")); var requestG = new Request(null, MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } // Two modules after two requests for same module, // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: true)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF, "A.F()"); VerifySignatures(requestG, "A.G()"); } // ... resolver enabled. moduleA = new Module(bytesA, name: "A.dll"); moduleB = new Module(bytesB, name: "B.dll"); using (var process = new Process(shouldEnable: false)) { var requestF = new Request("A.dll", MemberSignatureParser.Parse("F")); var requestG = new Request("A.dll", MemberSignatureParser.Parse("G")); resolver.EnableResolution(process, requestF); resolver.EnableResolution(process, requestG); Assert.Equal(0, process.ShouldEnableRequests); process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(2, process.ShouldEnableRequests); VerifySignatures(requestF); VerifySignatures(requestG); } } /// <summary> /// Should only handle requests with expected language id or /// default language id or causality breakpoints. /// </summary> [WorkItem(15119, "https://github.com/dotnet/roslyn/issues/15119")] [Fact] public void LanguageId() { var source = @"class C { static void F() { } }"; var bytes = CreateCompilation(source).EmitToArray(); var resolver = Resolver.CSharpResolver; var unknownId = Guid.Parse("F02FB87B-64EC-486E-B039-D4A97F48858C"); var csharpLanguageId = Guid.Parse("3f5162f8-07c6-11d3-9053-00c04fa302a1"); var vbLanguageId = Guid.Parse("3a12d0b8-c26c-11d0-b442-00a0244a1dd2"); var cppLanguageId = Guid.Parse("3a12d0b7-c26c-11d0-b442-00a0244a1dd2"); // Module loaded before requests. var module = new Module(bytes); using (var process = new Process(module)) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestDefaultId); VerifySignatures(requestDefaultId, "C.F()"); resolver.EnableResolution(process, requestUnknown); VerifySignatures(requestUnknown); resolver.EnableResolution(process, requestCausalityBreakpoint); VerifySignatures(requestCausalityBreakpoint, "C.F()"); resolver.EnableResolution(process, requestMethodId); VerifySignatures(requestMethodId); resolver.EnableResolution(process, requestCSharp); VerifySignatures(requestCSharp, "C.F()"); resolver.EnableResolution(process, requestVB); VerifySignatures(requestVB); resolver.EnableResolution(process, requestCPP); VerifySignatures(requestCPP); } // Module loaded after requests. module = new Module(bytes); using (var process = new Process()) { var requestDefaultId = new Request(null, MemberSignatureParser.Parse("F"), Guid.Empty); var requestUnknown = new Request(null, MemberSignatureParser.Parse("F"), unknownId); var requestCausalityBreakpoint = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.CausalityBreakpoint); var requestMethodId = new Request(null, MemberSignatureParser.Parse("F"), DkmLanguageId.MethodId); var requestCSharp = new Request(null, MemberSignatureParser.Parse("F"), csharpLanguageId); var requestVB = new Request(null, MemberSignatureParser.Parse("F"), vbLanguageId); var requestCPP = new Request(null, MemberSignatureParser.Parse("F"), cppLanguageId); resolver.EnableResolution(process, requestCPP); resolver.EnableResolution(process, requestVB); resolver.EnableResolution(process, requestCSharp); resolver.EnableResolution(process, requestMethodId); resolver.EnableResolution(process, requestCausalityBreakpoint); resolver.EnableResolution(process, requestUnknown); resolver.EnableResolution(process, requestDefaultId); process.AddModule(module); resolver.OnModuleLoad(process, module); VerifySignatures(requestDefaultId, "C.F()"); VerifySignatures(requestUnknown); VerifySignatures(requestCausalityBreakpoint, "C.F()"); VerifySignatures(requestMethodId); VerifySignatures(requestCSharp, "C.F()"); VerifySignatures(requestVB); VerifySignatures(requestCPP); } } [Fact] public void MissingMetadata() { var sourceA = @"class A { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var sourceC = @"class C { static void F1() { } static void F2() { } static void F3() { } static void F4() { } }"; var moduleA = new Module(CreateCompilation(sourceA).EmitToArray(), name: "A.dll"); var moduleB = new Module(default(ImmutableArray<byte>), name: "B.dll"); var moduleC = new Module(CreateCompilation(sourceC).EmitToArray(), name: "C.dll"); using (var process = new Process()) { var resolver = Resolver.CSharpResolver; var requestAll = new Request(null, MemberSignatureParser.Parse("F1")); var requestA = new Request("A.dll", MemberSignatureParser.Parse("F2")); var requestB = new Request("B.dll", MemberSignatureParser.Parse("F3")); var requestC = new Request("C.dll", MemberSignatureParser.Parse("F4")); // Request to all modules. resolver.EnableResolution(process, requestAll); Assert.Equal(0, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); // Load module A (available). process.AddModule(moduleA); resolver.OnModuleLoad(process, moduleA); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(0, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module B (missing). process.AddModule(moduleB); resolver.OnModuleLoad(process, moduleB); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(0, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Load module C (available). process.AddModule(moduleC); resolver.OnModuleLoad(process, moduleC); Assert.Equal(1, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module A (available). resolver.EnableResolution(process, requestA); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(1, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module B (missing). resolver.EnableResolution(process, requestB); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(1, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC); // Request to module C (available). resolver.EnableResolution(process, requestC); Assert.Equal(2, moduleA.MetadataAccessCount); Assert.Equal(2, moduleB.MetadataAccessCount); Assert.Equal(2, moduleC.MetadataAccessCount); VerifySignatures(requestAll, "A.F1()", "C.F1()"); VerifySignatures(requestA, "A.F2()"); VerifySignatures(requestB); VerifySignatures(requestC, "C.F4()"); } } [Fact] public void ModuleName() { var sourceA = @"public struct A { static void F() { } }"; var nameA = GetUniqueName(); var compilationA = CreateCompilation(sourceA, assemblyName: nameA); var imageA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(imageA).GetReference(); var sourceB = @"class B { static void F(A a) { } static void Main() { } }"; var nameB = GetUniqueName(); var compilationB = CreateCompilation(sourceB, assemblyName: nameB, options: TestOptions.DebugExe, references: new[] { refA }); var imageB = compilationB.EmitToArray(); using (var process = new Process(new Module(imageA, nameA + ".dll"), new Module(imageB, nameB + ".exe"))) { var signature = MemberSignatureParser.Parse("F"); var resolver = Resolver.CSharpResolver; // No module name. var request = new Request("", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()", "B.F(A)"); // DLL module name, uppercase. request = new Request(nameA.ToUpper() + ".DLL", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "A.F()"); // EXE module name. request = new Request(nameB + ".EXE", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, lowercase. request = new Request(nameB.ToLower() + ".exe", signature); resolver.EnableResolution(process, request); VerifySignatures(request, "B.F(A)"); // EXE module name, no extension. request = new Request(nameB, signature); resolver.EnableResolution(process, request); VerifySignatures(request); } } [Fact] [WorkItem(55475, "https://github.com/dotnet/roslyn/issues/55475")] public void BadMetadata() { var source = "class A { static void F() {} }"; var compilation = CreateCompilation(source); using var process = new Process( new Module(compilation.EmitToArray()), new Module(metadata: default), // emulates failure of the debugger to retrieve metadata new Module(metadata: TestResources.MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.ToImmutableArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.F()"); } [Fact] public void Arrays() { var source = @"class A { } class B { static void F(A o) { } static void F(A[] o) { } static void F(A[,,] o) { } static void F(A[,,][] o) { } static void F(A[][,,] o) { } static void F(A[][][] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(A)", "B.F(A[])", "B.F(A[,,])", "B.F(A[][,,])", "B.F(A[,,][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A)", "B.F(A)"); Resolve(process, resolver, "F(A[])", "B.F(A[])"); Resolve(process, resolver, "F(A[][])"); Resolve(process, resolver, "F(A[,])"); Resolve(process, resolver, "F(A[,,])", "B.F(A[,,])"); Resolve(process, resolver, "F(A[,,][])", "B.F(A[,,][])"); Resolve(process, resolver, "F(A[][,,])", "B.F(A[][,,])"); Resolve(process, resolver, "F(A[,][,,])"); Resolve(process, resolver, "F(A[][][])", "B.F(A[][][])"); Resolve(process, resolver, "F(A[][][][])"); } } [Fact] public void Pointers() { var source = @"class C { static unsafe void F(int*[] p) { } static unsafe void F(int** q) { } }"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Int32*[])", "C.F(System.Int32**)"); Resolve(process, resolver, "F(int)"); Resolve(process, resolver, "F(int*)"); Resolve(process, resolver, "F(int[])"); Resolve(process, resolver, "F(int*[])", "C.F(System.Int32*[])"); Resolve(process, resolver, "F(int**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(Int32**)", "C.F(System.Int32**)"); Resolve(process, resolver, "F(C<int*>)"); Resolve(process, resolver, "F(C<int>*)"); } } [Fact] public void Nullable() { var source = @"struct S { void F(S? o) { } static void F(int?[] o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "S.F(System.Nullable<S>)", "S.F(System.Nullable<System.Int32>[])"); Resolve(process, resolver, "F(S)"); Resolve(process, resolver, "F(S?)", "S.F(System.Nullable<S>)"); Resolve(process, resolver, "F(S??)"); Resolve(process, resolver, "F(int?[])", "S.F(System.Nullable<System.Int32>[])"); } } [Fact] public void ByRef() { var source = @"class @ref { } class @out { } class C { static void F(@out a, @ref b) { } static void F(ref @out a, out @ref b) { b = null; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(out, ref)", "C.F(ref out, ref ref)"); Assert.Null(MemberSignatureParser.Parse("F(ref, out)")); Assert.Null(MemberSignatureParser.Parse("F(ref ref, out out)")); Resolve(process, resolver, "F(@out, @ref)", "C.F(out, ref)"); Resolve(process, resolver, "F(@out, out @ref)"); Resolve(process, resolver, "F(ref @out, @ref)"); Resolve(process, resolver, "F(ref @out, out @ref)", "C.F(ref out, ref ref)"); Resolve(process, resolver, "F(out @out, ref @ref)", "C.F(ref out, ref ref)"); } } [Fact] public void Methods() { var source = @"abstract class A { abstract internal object F(); } class B { object F() => null; } class C { static object F() => null; } interface I { object F(); }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "C.F()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "B.F", "B.F()"); Resolve(process, resolver, "B.F()", "B.F()"); Resolve(process, resolver, "B.F(object)"); Resolve(process, resolver, "B.F<T>"); Resolve(process, resolver, "C.F", "C.F()"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Methods_ExplicitInterfaceImplementation() { var source = @" interface I { void F(); } interface J { void F(); } class C : I, J { class I { void F() { } } void global::I.F() { } void J.F() { } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F", "C.global::I.F()", "C.J.F()"); // resolves to the nested class members: Resolve(process, resolver, "C.I.F", "C.I.F()"); // does not resolve Resolve(process, resolver, "C.J.F"); } [Fact] public void Properties() { var source = @"abstract class A { abstract internal object P { get; set; } } class B { object P { get; set; } } class C { static object P { get; } } class D { int P { set { } } } interface I { object P { get; set; } }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "P", "B.get_P()", "B.set_P(System.Object)", "C.get_P()", "D.set_P(System.Int32)"); Resolve(process, resolver, "A.P"); Resolve(process, resolver, "B.P", "B.get_P()", "B.set_P(System.Object)"); Resolve(process, resolver, "B.P()"); Resolve(process, resolver, "B.P(object)"); Resolve(process, resolver, "B.P<T>"); Resolve(process, resolver, "C.P", "C.get_P()"); Resolve(process, resolver, "C.P()"); Resolve(process, resolver, "D.P", "D.set_P(System.Int32)"); Resolve(process, resolver, "D.P()"); Resolve(process, resolver, "D.P(object)"); Resolve(process, resolver, "get_P", "B.get_P()", "C.get_P()"); Resolve(process, resolver, "set_P", "B.set_P(System.Object)", "D.set_P(System.Int32)"); Resolve(process, resolver, "B.get_P()", "B.get_P()"); Resolve(process, resolver, "B.set_P", "B.set_P(System.Object)"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Properties_ExplicitInterfaceImplementation() { var source = @" interface I { int P { get; set; } } interface J { int P { get; set; } } class C : I, J { class I { int P { get; set; } } int global::I.P { get; set; } int J.P { get; set; } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.P", "C.global::I.get_P()", "C.global::I.set_P(System.Int32)", "C.J.get_P()", "C.J.set_P(System.Int32)"); Resolve(process, resolver, "C.get_P", "C.global::I.get_P()", "C.J.get_P()"); Resolve(process, resolver, "C.set_P", "C.global::I.set_P(System.Int32)", "C.J.set_P(System.Int32)"); // resolves to the nested class members: Resolve(process, resolver, "C.I.P", "C.I.get_P()", "C.I.set_P(System.Int32)"); Resolve(process, resolver, "C.I.get_P", "C.I.get_P()"); Resolve(process, resolver, "C.I.set_P", "C.I.set_P(System.Int32)"); // does not resolve Resolve(process, resolver, "C.J.P"); Resolve(process, resolver, "C.J.get_P"); Resolve(process, resolver, "C.J.set_P"); } [Fact] public void Events() { var source = @" abstract class A { abstract internal event System.Action E; } class B { event System.Action E; } class C { static event System.Action E; } class D { event System.Action E { add {} remove {} } } interface I { event System.Action E; }"; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "E", "B.add_E(System.Action)", "B.remove_E(System.Action)", "C.add_E(System.Action)", "C.remove_E(System.Action)", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "A.E"); Resolve(process, resolver, "B.E", "B.add_E(System.Action)", "B.remove_E(System.Action)"); Resolve(process, resolver, "B.E()"); Resolve(process, resolver, "B.E(System.Action)", "B.add_E(System.Action)", "B.remove_E(System.Action)"); Resolve(process, resolver, "B.E<T>"); Resolve(process, resolver, "C.E", "C.add_E(System.Action)", "C.remove_E(System.Action)"); Resolve(process, resolver, "C.E(System.Action)", "C.add_E(System.Action)", "C.remove_E(System.Action)"); Resolve(process, resolver, "D.E", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "D.E()"); Resolve(process, resolver, "D.E(System.Action)", "D.add_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "add_E", "B.add_E(System.Action)", "C.add_E(System.Action)", "D.add_E(System.Action)"); Resolve(process, resolver, "remove_E", "B.remove_E(System.Action)", "C.remove_E(System.Action)", "D.remove_E(System.Action)"); Resolve(process, resolver, "B.add_E(System.Action)", "B.add_E(System.Action)"); Resolve(process, resolver, "B.remove_E", "B.remove_E(System.Action)"); } [Fact] [WorkItem(4351, "https://github.com/MicrosoftDocs/visualstudio-docs/issues/4351")] [WorkItem(1303056, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1303056")] public void Events_ExplicitInterfaceImplementation() { var source = @" interface I { event System.Action E; } interface J { event System.Action E; } class C : I, J { class I { event System.Action E { add {} remove {} } } event System.Action global::I.E { add {} remove {} } event System.Action J.E { add {} remove {} } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.E", "C.global::I.add_E(System.Action)", "C.global::I.remove_E(System.Action)", "C.J.add_E(System.Action)", "C.J.remove_E(System.Action)"); Resolve(process, resolver, "C.add_E", "C.global::I.add_E(System.Action)", "C.J.add_E(System.Action)"); Resolve(process, resolver, "C.remove_E", "C.global::I.remove_E(System.Action)", "C.J.remove_E(System.Action)"); // resolves to the nested class members: Resolve(process, resolver, "C.I.E", "C.I.add_E(System.Action)", "C.I.remove_E(System.Action)"); Resolve(process, resolver, "C.I.add_E", "C.I.add_E(System.Action)"); Resolve(process, resolver, "C.I.remove_E", "C.I.remove_E(System.Action)"); // does not resolve Resolve(process, resolver, "C.J.E"); Resolve(process, resolver, "C.J.add_E"); Resolve(process, resolver, "C.J.remove_E"); } [Fact] public void Constructors() { var source = @"class A { static A() { } A() { } A(object o) { } } class B { } class C<T> { } class D { static object A => null; static void B<T>() { } } class E { static int x = 1; } "; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A", "A..cctor()", "A..ctor()", "A..ctor(System.Object)", "D.get_A()"); Resolve(process, resolver, "A.A", "A..cctor()", "A..ctor()", "A..ctor(System.Object)"); Resolve(process, resolver, "B", "B..ctor()"); Resolve(process, resolver, "B<T>", "D.B<T>()"); Resolve(process, resolver, "C", "C<T>..ctor()"); Resolve(process, resolver, "C<T>"); Resolve(process, resolver, "C<T>.C", "C<T>..ctor()"); Resolve(process, resolver, "E", "E..ctor()", "E..cctor()"); Assert.Null(MemberSignatureParser.Parse(".ctor")); Assert.Null(MemberSignatureParser.Parse("A..ctor")); } } [Fact] public void GenericMethods() { var source = @"class A { static void F() { } void F<T, U>() { } static void F<T>() { } } class A<T> { static void F() { } void F<U, V>() { } } class B : A<int> { static void F<T>() { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // Note, Dev14 matches type ignoring type parameters. For instance, // "A<T>.F" will bind to A.F() and A<T>.F(), and "A.F" will bind to A.F() // and A<T>.F. However, Dev14 does expect method type parameters to // match. Here, we expect both type and method parameters to match. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "A.F", "A.F()"); Resolve(process, resolver, "A.F<U>()", "A.F<T>()"); Resolve(process, resolver, "A.F<T>", "A.F<T>()"); Resolve(process, resolver, "A.F<T, T>", "A.F<T, U>()"); Assert.Null(MemberSignatureParser.Parse("A.F<>()")); Assert.Null(MemberSignatureParser.Parse("A.F<,>()")); Resolve(process, resolver, "A<T>.F", "A<T>.F()"); Resolve(process, resolver, "A<_>.F<_>"); Resolve(process, resolver, "A<_>.F<_, _>", "A<T>.F<U, V>()"); Resolve(process, resolver, "B.F()"); Resolve(process, resolver, "B.F<T>()", "B.F<T>()"); Resolve(process, resolver, "B.F<T, U>()"); } } [Fact] public void Namespaces() { var source = @"namespace N { namespace M { class A<T> { static void F() { } } } } namespace N { class B { static void F() { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "N.B.F()", "N.M.A<T>.F()"); Resolve(process, resolver, "A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.A<T>.F"); Resolve(process, resolver, "M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.M.A<T>.F", "N.M.A<T>.F()"); Resolve(process, resolver, "N.B.F", "N.B.F()"); } } [Fact] public void NestedTypes() { var source = @"class A { class B { static void F() { } } class B<T> { static void F<U>() { } } } class B { static void F() { } } namespace N { class A<T> { class B { static void F<U>() { } } class B<U> { static void F() { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { // See comment in GenericMethods regarding differences with Dev14. var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()", "A.B.F()", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "F<T>", "A.B<T>.F<U>()", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A.F"); Resolve(process, resolver, "A.B.F", "A.B.F()"); Resolve(process, resolver, "A.B.F<T>"); Resolve(process, resolver, "A.B<T>.F<U>", "A.B<T>.F<U>()"); Resolve(process, resolver, "A<T>.B.F<U>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "A<T>.B<U>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B.F", "B.F()", "A.B.F()"); Resolve(process, resolver, "B.F<T>", "N.A<T>.B.F<U>()"); Resolve(process, resolver, "B<T>.F", "N.A<T>.B<U>.F()"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>()"); Assert.Null(MemberSignatureParser.Parse("A+B.F")); Assert.Null(MemberSignatureParser.Parse("A.B`1.F<T>")); } } [Fact] public void NamespacesAndTypes() { var source = @"namespace A.B { class T { } class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } namespace A { class B<T> { internal class C { static void F(C c) { } static void F(A.B.C c) { } } } } class A<T> { internal class B { internal class C { static void F(C c) { } static void F(A.B<T>.C c) { } } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "F(C)", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B.C)", "A.B.C.F(A.B.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "F(B<T>.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A.B.C.F", "A.B.C.F(A.B.C)", "A.B.C.F(A.B<A.B.T>.C)"); Resolve(process, resolver, "A<T>.B.C.F", "A<T>.B.C.F(A<T>.B.C)", "A<T>.B.C.F(A.B<T>.C)"); Resolve(process, resolver, "A.B<T>.C.F", "A.B<T>.C.F(A.B<T>.C)", "A.B<T>.C.F(A.B.C)"); Resolve(process, resolver, "B<T>.C.F(B<T>.C)", "A.B<T>.C.F(A.B<T>.C)"); } } [Fact] public void NamespacesAndTypes_More() { var source = @"namespace A1.B { class C { static void F(C c) { } } } namespace A2 { class B { internal class C { static void F(C c) { } static void F(A1.B.C c) { } } } } class A3 { internal class B { internal class C { static void F(C c) { } static void F(A2.B.C c) { } } } } namespace B { class C { static void F(C c) { } static void F(A3.B.C c) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(B.C)", "B.C.F(B.C)", "B.C.F(A3.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A2.B.C)", "A2.B.C.F(A1.B.C)", "A3.B.C.F(A3.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A1.B.C)", "A1.B.C.F(A1.B.C)", "A2.B.C.F(A1.B.C)"); Resolve(process, resolver, "B.C.F(A2.B.C)", "A2.B.C.F(A2.B.C)", "A3.B.C.F(A2.B.C)"); Resolve(process, resolver, "B.C.F(A3.B.C)", "B.C.F(A3.B.C)", "A3.B.C.F(A3.B.C)"); } } [Fact] public void TypeParameters() { var source = @"class A { class B<T> { static void F<U>(B<T> t) { } static void F<U>(B<U> u) { } } } class A<T> { class B<U> { static void F<V>(T t) { } static void F<V>(A<U> u) { } static void F<V>(B<V> v) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "B<T>.F<U>", "A.B<T>.F<U>(A.B<T>)", "A.B<T>.F<U>(A.B<U>)", "A<T>.B<U>.F<V>(T)", "A<T>.B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); Resolve(process, resolver, "F<T>(B<T>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "F<U>(B<T>)"); // No T in signature to bind to. Resolve(process, resolver, "F<T>(B<U>)"); // No U in signature to bind to. Resolve(process, resolver, "B<X>.F<Y>(B<X>)", "A.B<T>.F<U>(A.B<T>)"); Resolve(process, resolver, "B<X>.F<Y>(B<Y>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<U>.F<V>(T)"); // No T in signature to bind to. Resolve(process, resolver, "B<U>.F<V>(A<U>)", "A<T>.B<U>.F<V>(A<U>)"); Resolve(process, resolver, "B<U>.F<V>(B<V>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "B<V>.F<U>(B<U>)", "A.B<T>.F<U>(A.B<U>)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(X)", "A<T>.B<U>.F<V>(T)"); Resolve(process, resolver, "A<X>.B<Y>.F<Z>(B<Z>)", "A<T>.B<U>.F<V>(A<T>.B<V>)"); } } [Fact] public void DifferentCase_MethodsAndProperties() { var source = @"class A { static void method() { } static void Method(object o) { } object property => null; } class B { static void Method() { } object Property { get; set; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "method", "A.method()"); Resolve(process, resolver, "Method", "A.Method(System.Object)", "B.Method()"); Resolve(process, resolver, "property", "A.get_property()"); Resolve(process, resolver, "Property", "B.get_Property()", "B.set_Property(System.Object)"); Resolve(process, resolver, "PROPERTY"); Resolve(process, resolver, "get_property", "A.get_property()"); Resolve(process, resolver, "GET_PROPERTY"); } } [Fact] public void DifferentCase_NamespacesAndTypes() { var source = @"namespace one.two { class THREE { static void Method(THREE t) { } } } namespace One.Two { class Three { static void Method(Three t) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "Method", "One.Two.Three.Method(One.Two.Three)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "three.Method"); Resolve(process, resolver, "Method(three)"); Resolve(process, resolver, "THREE.Method(THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "One.Two.Three.Method", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "ONE.TWO.THREE.Method"); Resolve(process, resolver, "Method(One.Two.Three)", "One.Two.Three.Method(One.Two.Three)"); Resolve(process, resolver, "Method(one.two.THREE)", "one.two.THREE.Method(one.two.THREE)"); Resolve(process, resolver, "Method(one.two.Three)"); Resolve(process, resolver, "THREE", "one.two.THREE..ctor()"); } } [Fact] public void TypeReferences() { var sourceA = @"public class A<T> { public class B<U> { static void F<V, W>() { } } } namespace N { public class C<T> { } }"; var compilationA = CreateCompilation(sourceA); var bytesA = compilationA.EmitToArray(); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var sourceB = @"class D<T> { static void F<U, V>(N.C<A<U>.B<V>[]> b) { } }"; var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesA), new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F<T, U>", "A<T>.B<U>.F<V, W>()", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(C)"); // No type argument for C<> Resolve(process, resolver, "F<T, U>(C<T>)"); // Incorrect type argument for C<> Resolve(process, resolver, "F<T, U>(C<B<U>>)"); // No array qualifier Resolve(process, resolver, "F<T, U>(C<B<T>[]>)"); // Incorrect type argument for B<> Resolve(process, resolver, "F<T, U>(C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "F<T, U>(N.C<B<U>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>[]>)"); // No nested type B Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Z>[]>)", "D<T>.F<U, V>(N.C<A<U>.B<V>[]>)"); Resolve(process, resolver, "D<X>.F<Y, Z>(C<A<Y>.B<Y>[]>)"); // Incorrect type argument for B<>. } } [Fact] public void Keywords_MethodName() { var source = @"namespace @namespace { struct @struct { object @public => 1; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("public")); Assert.Null(MemberSignatureParser.Parse("namespace.@struct.@public")); Assert.Null(MemberSignatureParser.Parse("@namespace.struct.@public")); Assert.Null(MemberSignatureParser.Parse("@[email protected]")); Resolve(process, resolver, "@public", "namespace.struct.get_public()"); Resolve(process, resolver, "@namespace.@struct.@public", "namespace.struct.get_public()"); } } [Fact] public void Keywords_MethodTypeParameter() { var source = @"class @class<@in> { static void F<@out>(@in i, @out o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F<out>")); Assert.Null(MemberSignatureParser.Parse("F<in>")); Assert.Null(MemberSignatureParser.Parse("class<@in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<in>.F<@out>")); Assert.Null(MemberSignatureParser.Parse("@class<@in>.F<out>")); Resolve(process, resolver, "F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "F<@in>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@in>.F<@out>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<@this>.F<@base>", "class<in>.F<out>(in, out)"); Resolve(process, resolver, "@class<T>.F<U>", "class<in>.F<out>(in, out)"); } } [Fact] public void Keywords_ParameterName() { var source = @"namespace @namespace { struct @struct { } } class C { static void F(@namespace.@struct s) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(struct)")); Assert.Null(MemberSignatureParser.Parse("F(namespace.@struct)")); Resolve(process, resolver, "F(@struct)", "C.F(namespace.struct)"); Resolve(process, resolver, "F(@namespace.@struct)", "C.F(namespace.struct)"); } } [Fact] public void Keywords_ParameterTypeArgument() { var source = @"class @this { internal class @base { } } class @class<T> { } class C { static void F(@class<@this.@base> c) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Assert.Null(MemberSignatureParser.Parse("F(@class<base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<this.@base>)")); Assert.Null(MemberSignatureParser.Parse("F(@class<@this.base>)")); Resolve(process, resolver, "F(@class<@base>)", "C.F(class<this.base>)"); Resolve(process, resolver, "F(@class<@this.@base>)", "C.F(class<this.base>)"); } } [Fact] public void EscapedNames() { var source = @"class @object { } class Object { } class C { static void F(@object o) { } static void F(Object o) { } static void F(object o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(Object)", "C.F(Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(System.Object)", "C.F(System.Object)"); Resolve(process, resolver, "F(@object)", "C.F(object)"); Resolve(process, resolver, "F(@Object)", "C.F(Object)", "C.F(System.Object)"); } } [Fact] public void SpecialTypes() { var source = @"class C<T1, T2, T3, T4> { } class C { static void F(bool a, char b, sbyte c, byte d) { } static void F(short a, ushort b, int c, uint d) { } static void F(C<uint, long, ulong, float> o) { } static void F(C<double, string, object, decimal> o) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(bool, char, sbyte, byte)", "C.F(System.Boolean, System.Char, System.SByte, System.Byte)"); Resolve(process, resolver, "F(System.Int16, System.UInt16, System.Int32, System.UInt32)", "C.F(System.Int16, System.UInt16, System.Int32, System.UInt32)"); Resolve(process, resolver, "F(C<UInt32, Int64, UInt64, Single>)", "C.F(C<System.UInt32, System.Int64, System.UInt64, System.Single>)"); Resolve(process, resolver, "F(C<double, string, object, decimal>)", "C.F(C<System.Double, System.String, System.Object, System.Decimal>)"); Resolve(process, resolver, "F(bool, char, sbyte)"); Resolve(process, resolver, "F(C<double, string, object, decimal, bool>)"); } } [Fact] public void SpecialTypes_More() { var source = @"class C { static void F(System.IntPtr p) { } static void F(System.UIntPtr p) { } static void F(System.TypedReference r) { } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F(object)"); Resolve(process, resolver, "F(IntPtr)", "C.F(System.IntPtr)"); Resolve(process, resolver, "F(UIntPtr)", "C.F(System.UIntPtr)"); Resolve(process, resolver, "F(TypedReference)", "C.F(System.TypedReference)"); } } // Binding to "dynamic" type refs is not supported. // This is consistent with Dev14. [Fact] public void Dynamic() { var source = @"class C<T> { } class C { static void F(dynamic d) { } static void F(C<dynamic[]> d) { } }"; var compilation = CreateCompilation(source, references: new[] { CSharpRef }); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F(System.Object)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(object)", "C.F(System.Object)"); Resolve(process, resolver, "F(C<object[]>)", "C.F(C<System.Object[]>)"); Resolve(process, resolver, "F(dynamic)"); Resolve(process, resolver, "F(C<dynamic[]>)"); } } [Fact] public void Iterator() { var source = @"class C { static System.Collections.IEnumerable F() { yield break; } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] public void Async() { var source = @"using System.Threading.Tasks; class C { static async Task F() { await Task.Delay(0); } }"; var compilation = CreateCompilationWithMscorlib46(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "C.F()"); } } [Fact] [WorkItem(55242, "https://github.com/dotnet/roslyn/issues/55242")] public void LocalFunctions() { var source = @" void F() { void G() { } } class F { void G() { void G() { } } } "; var compilation = CreateCompilation(source); using var process = new Process(new Module(compilation.EmitToArray())); var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "G", "Program.<<Main>$>g__G|0_1()", "F.G()", "F.<G>g__G|0_0()"); Resolve(process, resolver, "Program.G", "Program.<<Main>$>g__G|0_1()"); Resolve(process, resolver, "F.G", "F.G()", "F.<G>g__G|0_0()"); Resolve(process, resolver, "F.G.G"); } [Fact(Skip = "global:: not supported")] public void Global() { var source = @"class C { static void F(N.C o) { } static void F(global::C o) { } } namespace N { class C { static void F(N.C o) { } static void F(global::C o) { } } }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "C.F(C)", "C.F(N.C)", "C.F(C)", "N.C.F(N.C)", "N.C.F(C)"); Resolve(process, resolver, "C.F(N.C)", "C.F(N.C)", "N.C.F(N.C)"); Resolve(process, resolver, "global::C.F(C)", "C.F(N.C)", "C.F(C)"); // Dev14 does not bind global:: Resolve(process, resolver, "C.F(global::C)", "C.F(C)", "N.C.F(C)"); // Dev14 does not bind global:: } } // Since MetadataDecoder does not load referenced // assemblies, the arity or a type reference is determined // by the type name: e.g.: "C`2". If the arity from the name is // different from the number of generic type arguments, the // method signature containing the type reference is ignored. [Fact] public void UnexpectedArity() { var sourceA = @".class public A<T> { }"; var sourceB = @"class B { static void F(object o) { } static void F(A<object> a) { } }"; ImmutableArray<byte> bytesA; ImmutableArray<byte> pdbA; EmitILToArray(sourceA, appendDefaultHeader: true, includePdb: false, assemblyBytes: out bytesA, pdbBytes: out pdbA); var refA = AssemblyMetadata.CreateFromImage(bytesA).GetReference(); var compilationB = CreateCompilation(sourceB, references: new[] { refA }); var bytesB = compilationB.EmitToArray(); using (var process = new Process(new Module(bytesB))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F(System.Object)", "B.F([notsupported])"); Resolve(process, resolver, "F(A<object>)"); } } /// <summary> /// Should not resolve to P/Invoke methods. /// </summary> [Fact] public void PInvoke() { var source = @"using System.Runtime.InteropServices; class A { [DllImport(""extern.dll"")] public static extern int F(); } class B { public static int F() => 0; }"; var compilation = CreateCompilation(source); using (var process = new Process(new Module(compilation.EmitToArray()))) { var resolver = Resolver.CSharpResolver; Resolve(process, resolver, "F", "B.F()"); } } private static void Resolve(Process process, Resolver resolver, string str, params string[] expectedSignatures) { var signature = MemberSignatureParser.Parse(str); Assert.NotNull(signature); Resolve(process, resolver, signature, expectedSignatures); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/FileBannerFacts/AbstractFileBannerFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractFileBannerFacts : IFileBannerFacts { // Matches the following: // // (whitespace* newline)+ private readonly Matcher<SyntaxTrivia> _oneOrMoreBlankLines; // Matches the following: // // (whitespace* (single-comment|multi-comment) whitespace* newline)+ OneOrMoreBlankLines private readonly Matcher<SyntaxTrivia> _bannerMatcher; // Used to match the following: // // <start-of-file> (whitespace* (single-comment|multi-comment) whitespace* newline)+ blankLine* private readonly Matcher<SyntaxTrivia> _fileBannerMatcher; protected AbstractFileBannerFacts() { var whitespace = Matcher.Repeat( Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsWhitespaceTrivia, "\\b")); var endOfLine = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsEndOfLineTrivia, "\\n"); var singleBlankLine = Matcher.Sequence(whitespace, endOfLine); var shebangComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsShebangDirectiveTrivia, "#!"); var singleLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineCommentTrivia, "//"); var multiLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineCommentTrivia, "/**/"); var singleLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineDocCommentTrivia, "///"); var multiLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineDocCommentTrivia, "/** */"); var anyCommentMatcher = Matcher.Choice(shebangComment, singleLineComment, multiLineComment, singleLineDocumentationComment, multiLineDocumentationComment); var commentLine = Matcher.Sequence(whitespace, anyCommentMatcher, whitespace, endOfLine); _oneOrMoreBlankLines = Matcher.OneOrMore(singleBlankLine); _bannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), _oneOrMoreBlankLines); _fileBannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), Matcher.Repeat(singleBlankLine)); } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract IDocumentationCommentService DocumentationCommentService { get; } public string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken) => DocumentationCommentService.GetBannerText(documentationCommentTriviaSyntax, bannerLength, cancellationToken); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node) => GetLeadingBlankLines<SyntaxNode>(node); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBlankLines(node, out var blankLines); return blankLines; } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBlankLines(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTriviaToKeep = new List<SyntaxTrivia>(node.GetLeadingTrivia()); var index = 0; _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index); strippedTrivia = leadingTriviaToKeep.Take(index).ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out var leadingTrivia); return leadingTrivia; } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTrivia = node.GetLeadingTrivia(); // Rules for stripping trivia: // 1) If there is a pp directive, then it (and all preceding trivia) *must* be stripped. // This rule supersedes all other rules. // 2) If there is a doc comment, it cannot be stripped. Even if there is a doc comment, // followed by 5 new lines, then the doc comment still must stay with the node. This // rule does *not* supersede rule 1. // 3) Single line comments in a group (i.e. with no blank lines between them) belong to // the node *iff* there is no blank line between it and the following trivia. List<SyntaxTrivia> leadingTriviaToStrip, leadingTriviaToKeep; var ppIndex = -1; for (var i = leadingTrivia.Count - 1; i >= 0; i--) { if (this.SyntaxFacts.IsPreprocessorDirective(leadingTrivia[i])) { ppIndex = i; break; } } if (ppIndex != -1) { // We have a pp directive. it (and all previous trivia) must be stripped. leadingTriviaToStrip = new List<SyntaxTrivia>(leadingTrivia.Take(ppIndex + 1)); leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia.Skip(ppIndex + 1)); } else { leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia); leadingTriviaToStrip = new List<SyntaxTrivia>(); } // Now, consume as many banners as we can. s_fileBannerMatcher will only be matched at // the start of the file. var index = 0; while ( _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index) || _bannerMatcher.TryMatch(leadingTriviaToKeep, ref index) || (node.FullSpan.Start == 0 && _fileBannerMatcher.TryMatch(leadingTriviaToKeep, ref index))) { } leadingTriviaToStrip.AddRange(leadingTriviaToKeep.Take(index)); strippedTrivia = leadingTriviaToStrip.ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root) { Debug.Assert(root.FullSpan.Start == 0); return GetFileBanner(root.GetFirstToken(includeZeroWidth: true)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken) { Debug.Assert(firstToken.FullSpan.Start == 0); var leadingTrivia = firstToken.LeadingTrivia; var index = 0; _fileBannerMatcher.TryMatch(leadingTrivia.ToList(), ref index); return ImmutableArray.CreateRange(leadingTrivia.Take(index)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractFileBannerFacts : IFileBannerFacts { // Matches the following: // // (whitespace* newline)+ private readonly Matcher<SyntaxTrivia> _oneOrMoreBlankLines; // Matches the following: // // (whitespace* (single-comment|multi-comment) whitespace* newline)+ OneOrMoreBlankLines private readonly Matcher<SyntaxTrivia> _bannerMatcher; // Used to match the following: // // <start-of-file> (whitespace* (single-comment|multi-comment) whitespace* newline)+ blankLine* private readonly Matcher<SyntaxTrivia> _fileBannerMatcher; protected AbstractFileBannerFacts() { var whitespace = Matcher.Repeat( Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsWhitespaceTrivia, "\\b")); var endOfLine = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsEndOfLineTrivia, "\\n"); var singleBlankLine = Matcher.Sequence(whitespace, endOfLine); var shebangComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsShebangDirectiveTrivia, "#!"); var singleLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineCommentTrivia, "//"); var multiLineComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineCommentTrivia, "/**/"); var singleLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsSingleLineDocCommentTrivia, "///"); var multiLineDocumentationComment = Matcher.Single<SyntaxTrivia>(this.SyntaxFacts.IsMultiLineDocCommentTrivia, "/** */"); var anyCommentMatcher = Matcher.Choice(shebangComment, singleLineComment, multiLineComment, singleLineDocumentationComment, multiLineDocumentationComment); var commentLine = Matcher.Sequence(whitespace, anyCommentMatcher, whitespace, endOfLine); _oneOrMoreBlankLines = Matcher.OneOrMore(singleBlankLine); _bannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), _oneOrMoreBlankLines); _fileBannerMatcher = Matcher.Sequence( Matcher.OneOrMore(commentLine), Matcher.Repeat(singleBlankLine)); } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract IDocumentationCommentService DocumentationCommentService { get; } public string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int bannerLength, CancellationToken cancellationToken) => DocumentationCommentService.GetBannerText(documentationCommentTriviaSyntax, bannerLength, cancellationToken); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node) => GetLeadingBlankLines<SyntaxNode>(node); public ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBlankLines(node, out var blankLines); return blankLines; } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBlankLines(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTriviaToKeep = new List<SyntaxTrivia>(node.GetLeadingTrivia()); var index = 0; _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index); strippedTrivia = leadingTriviaToKeep.Take(index).ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode { GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out var leadingTrivia); return leadingTrivia; } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node) where TSyntaxNode : SyntaxNode { return GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out _); } public TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>( TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode { var leadingTrivia = node.GetLeadingTrivia(); // Rules for stripping trivia: // 1) If there is a pp directive, then it (and all preceding trivia) *must* be stripped. // This rule supersedes all other rules. // 2) If there is a doc comment, it cannot be stripped. Even if there is a doc comment, // followed by 5 new lines, then the doc comment still must stay with the node. This // rule does *not* supersede rule 1. // 3) Single line comments in a group (i.e. with no blank lines between them) belong to // the node *iff* there is no blank line between it and the following trivia. List<SyntaxTrivia> leadingTriviaToStrip, leadingTriviaToKeep; var ppIndex = -1; for (var i = leadingTrivia.Count - 1; i >= 0; i--) { if (this.SyntaxFacts.IsPreprocessorDirective(leadingTrivia[i])) { ppIndex = i; break; } } if (ppIndex != -1) { // We have a pp directive. it (and all previous trivia) must be stripped. leadingTriviaToStrip = new List<SyntaxTrivia>(leadingTrivia.Take(ppIndex + 1)); leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia.Skip(ppIndex + 1)); } else { leadingTriviaToKeep = new List<SyntaxTrivia>(leadingTrivia); leadingTriviaToStrip = new List<SyntaxTrivia>(); } // Now, consume as many banners as we can. s_fileBannerMatcher will only be matched at // the start of the file. var index = 0; while ( _oneOrMoreBlankLines.TryMatch(leadingTriviaToKeep, ref index) || _bannerMatcher.TryMatch(leadingTriviaToKeep, ref index) || (node.FullSpan.Start == 0 && _fileBannerMatcher.TryMatch(leadingTriviaToKeep, ref index))) { } leadingTriviaToStrip.AddRange(leadingTriviaToKeep.Take(index)); strippedTrivia = leadingTriviaToStrip.ToImmutableArray(); return node.WithLeadingTrivia(leadingTriviaToKeep.Skip(index)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root) { Debug.Assert(root.FullSpan.Start == 0); return GetFileBanner(root.GetFirstToken(includeZeroWidth: true)); } public ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken) { Debug.Assert(firstToken.FullSpan.Start == 0); var leadingTrivia = firstToken.LeadingTrivia; var index = 0; _fileBannerMatcher.TryMatch(leadingTrivia.ToList(), ref index); return ImmutableArray.CreateRange(leadingTrivia.Take(index)); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEncapsulateField.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicEncapsulateField : AbstractEditorTest { public BasicEncapsulateField(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicEncapsulateField)) { } protected override string LanguageName => LanguageNames.VisualBasic; private const string TestSource = @" Module Module1 Public $$name As Integer? = 0 Sub Main() name = 90 End Sub End Module"; [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35701")] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughCommand() { SetUpEditor(TestSource); var encapsulateField = VisualStudio.EncapsulateField; var dialog = VisualStudio.PreviewChangesDialog; encapsulateField.Invoke(); dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout); dialog.ClickCancel(encapsulateField.DialogName); dialog.VerifyClosed(encapsulateField.DialogName); encapsulateField.Invoke(); dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout); dialog.ClickApplyAndWaitForFeature(encapsulateField.DialogName, FeatureAttribute.EncapsulateField); VisualStudio.Editor.Verify.TextContains(@" Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property"); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughLightbulbIncludingReferences() { SetUpEditor(TestSource); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (and use property)", applyFix: true, blockUntilComplete: true); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property Sub Main() Name = 90 End Sub End Module"); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughLightbulbDefinitionsOnly() { SetUpEditor(TestSource); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (but still use field)", applyFix: true, blockUntilComplete: true); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property Sub Main() name = 90 End Sub End Module"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicEncapsulateField : AbstractEditorTest { public BasicEncapsulateField(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicEncapsulateField)) { } protected override string LanguageName => LanguageNames.VisualBasic; private const string TestSource = @" Module Module1 Public $$name As Integer? = 0 Sub Main() name = 90 End Sub End Module"; [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35701")] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughCommand() { SetUpEditor(TestSource); var encapsulateField = VisualStudio.EncapsulateField; var dialog = VisualStudio.PreviewChangesDialog; encapsulateField.Invoke(); dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout); dialog.ClickCancel(encapsulateField.DialogName); dialog.VerifyClosed(encapsulateField.DialogName); encapsulateField.Invoke(); dialog.VerifyOpen(encapsulateField.DialogName, timeout: Helper.HangMitigatingTimeout); dialog.ClickApplyAndWaitForFeature(encapsulateField.DialogName, FeatureAttribute.EncapsulateField); VisualStudio.Editor.Verify.TextContains(@" Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property"); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughLightbulbIncludingReferences() { SetUpEditor(TestSource); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (and use property)", applyFix: true, blockUntilComplete: true); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property Sub Main() Name = 90 End Sub End Module"); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateThroughLightbulbDefinitionsOnly() { SetUpEditor(TestSource); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (but still use field)", applyFix: true, blockUntilComplete: true); VisualStudio.Editor.Verify.TextContains(@" Module Module1 Private _name As Integer? = 0 Public Property Name As Integer? Get Return _name End Get Set(value As Integer?) _name = value End Set End Property Sub Main() name = 90 End Sub End Module"); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/Core/Def/Implementation/Extensions/VsTextSpanExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class VsTextSpanExtensions { public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer) { spanInPrimaryBuffer = default; if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } var bufferCoordinator = containedDocument.BufferCoordinator; var primary = new VsTextSpan[1]; var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary); spanInPrimaryBuffer = primary[0]; return ErrorHandler.Succeeded(hresult); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class VsTextSpanExtensions { public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer) { spanInPrimaryBuffer = default; if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } var bufferCoordinator = containedDocument.BufferCoordinator; var primary = new VsTextSpan[1]; var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary); spanInPrimaryBuffer = primary[0]; return ErrorHandler.Succeeded(hresult); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/EditorFeatures/CSharp/BlockCommentEditing/CloseBlockCommentCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(CloseBlockCommentCommandHandler))] [Order(After = nameof(BlockCommentEditingCommandHandler))] internal sealed class CloseBlockCommentCommandHandler : ICommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CloseBlockCommentCommandHandler() { } public string DisplayName => EditorFeaturesResources.Block_Comment_Editing; public bool ExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar == '/') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var (snapshot, position) = caret.Value; // Check that the line is all whitespace ending with an asterisk and a single space (| marks caret position): // * | if (position >= 2 && snapshot[position - 1] == ' ' && snapshot[position - 2] == '*') { var line = snapshot.GetLineFromPosition(position); if (line.End == position && line.IsEmptyOrWhitespace(0, line.Length - 2)) { if (args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString) && BlockCommentEditingCommandHandler.IsCaretInsideBlockCommentSyntax(caret.Value, out _, out _)) { args.SubjectBuffer.Replace(new VisualStudio.Text.Span(position - 1, 1), "/"); return true; } } } } } return false; } public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Unspecified; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.BlockCommentEditing { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(CloseBlockCommentCommandHandler))] [Order(After = nameof(BlockCommentEditingCommandHandler))] internal sealed class CloseBlockCommentCommandHandler : ICommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CloseBlockCommentCommandHandler() { } public string DisplayName => EditorFeaturesResources.Block_Comment_Editing; public bool ExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext) { if (args.TypedChar == '/') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var (snapshot, position) = caret.Value; // Check that the line is all whitespace ending with an asterisk and a single space (| marks caret position): // * | if (position >= 2 && snapshot[position - 1] == ' ' && snapshot[position - 2] == '*') { var line = snapshot.GetLineFromPosition(position); if (line.End == position && line.IsEmptyOrWhitespace(0, line.Length - 2)) { if (args.SubjectBuffer.GetFeatureOnOffOption(FeatureOnOffOptions.AutoInsertBlockCommentStartString) && BlockCommentEditingCommandHandler.IsCaretInsideBlockCommentSyntax(caret.Value, out _, out _)) { args.SubjectBuffer.Replace(new VisualStudio.Text.Span(position - 1, 1), "/"); return true; } } } } } return false; } public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Unspecified; } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IIsTypeExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IIsTypeExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionStringType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { object o = myStr; bool b = /*<bind>*/o is string/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is string') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: System.String "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionIntType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { int myInt = 3; bool b = /*<bind>*/myInt is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'myInt is int') Operand: ILocalReferenceOperation: myInt (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'myInt') IsType: System.Int32 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0183: The given expression is always of the provided ('int') type // bool b = /*<bind>*/myInt is int/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "myInt is int").WithArguments("int").WithLocation(13, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/o is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is TestType') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: TestIsOperator.TestType "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_NullExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/null is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'null is TestType') Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IsType: TestIsOperator.TestType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('TestType') type // bool b = /*<bind>*/null is TestType/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is TestType").WithArguments("TestIsOperator.TestType").WithLocation(14, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionEnumType() { string source = @" class IsTest { static void Main() { var b = /*<bind>*/1 is color/*</bind>*/; System.Console.WriteLine(b); } } enum color { } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '1 is color') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IsType: color "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('color') type // var b = /*<bind>*/1 is color/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is color").WithArguments("color").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionIntType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is int') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionObjectType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/u is object/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'u is object') Operand: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: U) (Syntax: 'u') IsType: System.Object "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionDifferentTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is U/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is U') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: U "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionSameTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is T/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is T') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: T "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_01() { string source = @" class C { public static void M2(C1 c, bool b) /*<bind>*/{ b = c is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = c is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = c is C1') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'c is C1') Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c') IsType: C.C1 Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_02() { string source = @" class C { public static void M2(C1 c1, C1 c2, bool b) /*<bind>*/{ b = (c1 ?? c2) is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (c1 ?? c2) is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (c1 ?? c2) is C1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '(c1 ?? c2) is C1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1 ?? c2') IsType: C.C1 Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IIsTypeExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionStringType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { object o = myStr; bool b = /*<bind>*/o is string/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is string') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: System.String "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionIntType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { int myInt = 3; bool b = /*<bind>*/myInt is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'myInt is int') Operand: ILocalReferenceOperation: myInt (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'myInt') IsType: System.Int32 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0183: The given expression is always of the provided ('int') type // bool b = /*<bind>*/myInt is int/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "myInt is int").WithArguments("int").WithLocation(13, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/o is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is TestType') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: TestIsOperator.TestType "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_NullExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/null is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'null is TestType') Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IsType: TestIsOperator.TestType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('TestType') type // bool b = /*<bind>*/null is TestType/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is TestType").WithArguments("TestIsOperator.TestType").WithLocation(14, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionEnumType() { string source = @" class IsTest { static void Main() { var b = /*<bind>*/1 is color/*</bind>*/; System.Console.WriteLine(b); } } enum color { } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '1 is color') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IsType: color "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('color') type // var b = /*<bind>*/1 is color/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is color").WithArguments("color").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionIntType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is int') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionObjectType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/u is object/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'u is object') Operand: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: U) (Syntax: 'u') IsType: System.Object "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionDifferentTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is U/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is U') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: U "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionSameTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is T/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is T') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: T "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_01() { string source = @" class C { public static void M2(C1 c, bool b) /*<bind>*/{ b = c is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = c is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = c is C1') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'c is C1') Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c') IsType: C.C1 Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_02() { string source = @" class C { public static void M2(C1 c1, C1 c2, bool b) /*<bind>*/{ b = (c1 ?? c2) is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (c1 ?? c2) is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (c1 ?? c2) is C1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '(c1 ?? c2) is C1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1 ?? c2') IsType: C.C1 Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/EditorFeatures/CSharpTest/RefactoringHelpers/RefactoringHelpersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RefactoringHelpers { public partial class RefactoringHelpersTests : RefactoringHelpersTestBase<CSharpTestWorkspaceFixture> { #region Locations [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Local[||]Function(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestAfterTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTokenUnderDifferentNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbRightEdge() { var testText = @" class C { void M() { {|result:C LocalFunction(C c) { return null; }[||]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdge() { var testText = @" class C { void M() { {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeComments() { var testText = @" class C { void M() { /// <summary> /// Comment1 /// </summary> {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInAnotherChildNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTooFarBeforeInWhitespace() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() { var testText = @" class C { void M() { var a = null; [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNotBeforePrecedingComment() { var testText = @" class C { void M() { [||]//Test comment C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnSameLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnPreviousLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace2() { var testText = @" class C { void M() { var a = null; [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInNextTokensLeadingTrivia() { var testText = @" class C { void M() { C LocalFunction(C c) { return null; } [||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInEmptySyntaxNode() { var testText = @" class C { void M() { N(0, N(0, [||]{|result:|}, 0)); } int N(int a, int b, int c) { } }"; await TestAsync<ArgumentSyntax>(testText); } #endregion #region Selections [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [|LocalFunction|](C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPartiallySelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Lo[|calFunct|]ion(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedMultipleTokensUnderNode() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c)|] { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() { var testText = @" class C { void M() { C LocalFunction(C c) [|{ return null; }|] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedLowerNode() { var testText = @" class C { void M() { [|C|] LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace() { var testText = @" class C { void M() { C[| |]LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace2() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestCompleteSelection() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c) { return null; }|]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelection() { var testText = @" class C { void M() { [| {|result:C LocalFunction(C c) { return null; }|} |]var a = new object(); } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelectionComments() { var testText = @" class C { void M() { // Co[|mment1 {|result:C LocalFunction(C c) { return null; }|}|] } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingOverSelection() { var testText = @" class C { void M() { [| C LocalFunction(C c) { return null; } v|]ar a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectionBefore() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } var a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region IsUnderselected [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionOnSemicolon() { var testText = @" class Program { static void Main() { {|result:Main()|}[|;|] } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug1() { var testText = @" class Program { public static void Method() { //[|> var str = {|result:"" <|] aaa""|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug2() { var testText = @" class C { public void M() { Console.WriteLine(""Hello world"");[| {|result:Console.WriteLine(new |]C())|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection() { var testText = @" class C { public void M() { bool a = {|result:[|true || false || true|]|}; }"; await TestNotUnderselectedAsync<BinaryExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection2() { var testText = @" class C { public void M() { bool a = true || [|false || true|] || true; }"; await TestUnderselectedAsync<BinaryExpressionSyntax>(testText); } #endregion #region Attributes [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember() { var testText = @" using System; public class Class1 { [][||] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute() { var testText = @" using System; public class Class1 { {|result:void foo([[||]bar) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute2() { var testText = @" using System; public class Class1 { {|result:void foo([[||]Class1 arg1) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37837, "https://github.com/dotnet/roslyn/issues/37837")] public async Task TestEmptyParameter() { var testText = @" using System; public class TestAttribute : Attribute { } public class Class1 { static void foo({|result:[Test][||] |} { } }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember2() { var testText = @" using System; public class Class1 { [||]// Comment [] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestEmptyAttributeList() { var testText = @" using System; public class Class1 { {|result:[] [||]void a() {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeBeforeAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 [||]{|result:[Test] void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributeComments() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 {|result:[Test] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [Test] [||][Test2] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } [[||]Test] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [|[Test] [Test2]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } [|[Test]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeAndAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 [|{|result:[Test] [Test2] // Comment2 void M() { }|}|] }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeWithoutAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [|void M() { }|]|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region Extractions general [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractionsClimbing() { var testText = @" using System; class C { void M() { var a = {|result:new object()|};[||] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractHeaderForSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public [|int|] a { get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultipleExtractions() { var localDeclaration = "{|result:string name = \"\", b[||]b = null;|}"; var localDeclarator = "string name = \"\", {|result:bb[||] = null|};"; await TestAsync<LocalDeclarationStatementSyntax>(GetTestText(localDeclaration)); await TestAsync<VariableDeclaratorSyntax>(GetTestText(localDeclarator)); static string GetTestText(string data) { return @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; } } #endregion #region Extractions [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration() { var testText = @" using System; class C { void M() { [|var a = {|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration2() { var testText = @" using System; class C { void M() { var a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromAssignment() { var testText = @" using System; class C { void M() { object a; a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator() { var testText = @" using System; class C { void M() { var [|a = {|result:new object()|}|]; } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator2() { var testText = @" using System; class C { void M() { {|result:var [|a = new object()|];|} } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] public i[||]nt a { get; set; }|} }"; await TestAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractNotInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public int a { [||]get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } #endregion #region Headers & holes [Theory] [InlineData("var aa = nul[||]l;")] [InlineData("var aa = n[||]ull;")] [InlineData("string aa = null, bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInHeaderHole(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("{|result:[||]var aa = null;|}")] [InlineData("{|result:var aa = [||]null;|}")] [InlineData("{|result:var aa = null[||];|}")] [InlineData("{|result:string aa = null, b[||]b = null;|}")] [InlineData("{|result:string aa = null, bb = [||]null;|}")] [InlineData("{|result:string aa = null, bb = null[||];|}")] [InlineData("{|result:string aa = null, bb = null;[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region TestHidden [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden2() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} #line hidden var a = b; #line default } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingHidden() { var testText = @" #line default class C { void M() { #line hidden C LocalFunction(C c) #line default { return null; }[||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region Test predicate [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingPredicate() { var testText = @" class C { void M() { N([||]2+3); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgument() { var testText = @" class C { void M() { N({|result:[||]2+3|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPredicate() { var testText = @" class C { void M() { var a = ({|result:[||]2 + 3|}, 2 + 3); } }"; await TestAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } #endregion #region Test arguments [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = [||]42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = [|42|], int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectComma() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = 42[|,|] int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([[||]Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|int|] a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|C|] a = null, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsAtTheEnd() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = 42[||]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsBefore() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([||]{|result:[Test]int a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParamName() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int [|a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([|{|result:[Test]int a = 42|}|], int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam3() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a = 42|]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } public CC({|result:[Test]C[||]C a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } #endregion #region Test methods [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingMethodExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } public void [|I|].A([Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodCaretBeforeInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [||]I.A([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodNameAndExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [|I.A|]([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } {|result:public C[||]C I.A([Test]int a = 42, int b = 41) { return null; }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region TestLocalDeclaration [Theory] [InlineData("{|result:v[||]ar name = \"\";|}")] [InlineData("{|result:string name = \"\", b[||]b = null;|}")] [InlineData("{|result:var[||] name = \"\";|}")] [InlineData("{|result:var [||]name = \"\";|}")] [InlineData("{|result:var na[||]me = \"\";|}")] [InlineData("{|result:var name[||] = \"\";|}")] [InlineData("{|result:var name [||]= \"\";|}")] [InlineData("{|result:var name =[||] \"\";|}")] [InlineData("{|result:var name = [||]\"\";|}")] [InlineData("{|result:[|var name = \"\";|]|}")] [InlineData("{|result:var name = \"\"[||];|}")] [InlineData("{|result:var name = \"\";[||]|}")] [InlineData("{|result:var name = \"\"[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestLocalDeclarationInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("var name = \"[||]\";")] [InlineData("var name=[|\"\"|];")] [InlineData("string name = \"\", bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingLocalDeclarationCaretInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region Test Ifs [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection1() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); }|] else if (b) { b(); } else { c(); }|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection2() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); } else if (b) { b(); } else { c(); }|]|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMissingMultiline_IfElseIfElseSelection() { await TestMissingAsync<IfStatementSyntax>( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } #endregion #region Test Deep in expression [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepIn() { var testText = @" class C { void M() { N({|result:2+[||]3+4|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingDeepInSecondRow() { var testText = @" class C { void M() { N(2 +[||]3+4); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepInExpression() { var testText = @" class C { void M() { var b = ({|result:N(2[||])|}, 0); } int N(int a) { return a; } }"; await TestAsync<ArgumentSyntax>(testText, predicate: n => n.Parent is TupleExpressionSyntax); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.RefactoringHelpers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RefactoringHelpers { public partial class RefactoringHelpersTests : RefactoringHelpersTestBase<CSharpTestWorkspaceFixture> { #region Locations [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Local[||]Function(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestAfterTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTokenUnderDifferentNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbRightEdge() { var testText = @" class C { void M() { {|result:C LocalFunction(C c) { return null; }[||]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdge() { var testText = @" class C { void M() { {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeComments() { var testText = @" class C { void M() { /// <summary> /// Comment1 /// </summary> {|result:[||]C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInAnotherChildNode() { var testText = @" class C { void M() { C LocalFunction(C c) { [||]return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInTooFarBeforeInWhitespace() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInWhiteSpaceOnLineWithDifferentStatement() { var testText = @" class C { void M() { var a = null; [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNotBeforePrecedingComment() { var testText = @" class C { void M() { [||]//Test comment C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnSameLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_OnPreviousLine() { var testText = @" class C { void M() { [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace1_NotOnMultipleLinesPrior() { var testText = @" class C { void M() { [||] C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestBeforeInWhitespace2() { var testText = @" class C { void M() { var a = null; [||] {|result:C LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInNextTokensLeadingTrivia() { var testText = @" class C { void M() { C LocalFunction(C c) { return null; } [||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInEmptySyntaxNode() { var testText = @" class C { void M() { N(0, N(0, [||]{|result:|}, 0)); } int N(int a, int b, int c) { } }"; await TestAsync<ArgumentSyntax>(testText); } #endregion #region Selections [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C [|LocalFunction|](C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPartiallySelectedTokenDirectlyUnderNode() { var testText = @" class C { void M() { {|result:C Lo[|calFunct|]ion(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedMultipleTokensUnderNode() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c)|] { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedMultipleTokensWithLowerCommonAncestor() { var testText = @" class C { void M() { C LocalFunction(C c) [|{ return null; }|] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedLowerNode() { var testText = @" class C { void M() { [|C|] LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace() { var testText = @" class C { void M() { C[| |]LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedWhitespace2() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestCompleteSelection() { var testText = @" class C { void M() { {|result:[|C LocalFunction(C c) { return null; }|]|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelection() { var testText = @" class C { void M() { [| {|result:C LocalFunction(C c) { return null; }|} |]var a = new object(); } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestOverSelectionComments() { var testText = @" class C { void M() { // Co[|mment1 {|result:C LocalFunction(C c) { return null; }|}|] } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingOverSelection() { var testText = @" class C { void M() { [| C LocalFunction(C c) { return null; } v|]ar a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectionBefore() { var testText = @" class C { void M() { [| |]C LocalFunction(C c) { return null; } var a = new object(); } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region IsUnderselected [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionOnSemicolon() { var testText = @" class Program { static void Main() { {|result:Main()|}[|;|] } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug1() { var testText = @" class Program { public static void Method() { //[|> var str = {|result:"" <|] aaa""|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselectionBug2() { var testText = @" class C { public void M() { Console.WriteLine(""Hello world"");[| {|result:Console.WriteLine(new |]C())|}; } }"; await TestNotUnderselectedAsync<ExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection() { var testText = @" class C { public void M() { bool a = {|result:[|true || false || true|]|}; }"; await TestNotUnderselectedAsync<BinaryExpressionSyntax>(testText); } [Fact] [WorkItem(38708, "https://github.com/dotnet/roslyn/issues/38708")] public async Task TestUnderselection2() { var testText = @" class C { public void M() { bool a = true || [|false || true|] || true; }"; await TestUnderselectedAsync<BinaryExpressionSyntax>(testText); } #endregion #region Attributes [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember() { var testText = @" using System; public class Class1 { [][||] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute() { var testText = @" using System; public class Class1 { {|result:void foo([[||]bar) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(38502, "https://github.com/dotnet/roslyn/issues/38502")] public async Task TestIncompleteAttribute2() { var testText = @" using System; public class Class1 { {|result:void foo([[||]Class1 arg1) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37837, "https://github.com/dotnet/roslyn/issues/37837")] public async Task TestEmptyParameter() { var testText = @" using System; public class TestAttribute : Attribute { } public class Class1 { static void foo({|result:[Test][||] |} { } }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestMissingEmptyMember2() { var testText = @" using System; public class Class1 { [||]// Comment [] }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(37584, "https://github.com/dotnet/roslyn/issues/37584")] public async Task TestEmptyAttributeList() { var testText = @" using System; public class Class1 { {|result:[] [||]void a() {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeBeforeAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 [||]{|result:[Test] void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributeComments() { var testText = @" using System; class C { class TestAttribute : Attribute { } // Comment1 {|result:[Test] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestClimbLeftEdgeAfterAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [||]void M() { }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [Test] [||][Test2] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingBetweenInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } [[||]Test] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } [|[Test] [Test2]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingSelectedAttribute() { var testText = @" using System; class C { class TestAttribute : Attribute { } [|[Test]|] void M() { } }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeAndAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 [|{|result:[Test] [Test2] // Comment2 void M() { }|}|] }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestSelectedWholeNodeWithoutAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } // Comment1 {|result:[Test] [Test2] // Comment2 [|void M() { }|]|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region Extractions general [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractionsClimbing() { var testText = @" using System; class C { void M() { var a = {|result:new object()|};[||] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractHeaderForSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public [|int|] a { get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMultipleExtractions() { var localDeclaration = "{|result:string name = \"\", b[||]b = null;|}"; var localDeclarator = "string name = \"\", {|result:bb[||] = null|};"; await TestAsync<LocalDeclarationStatementSyntax>(GetTestText(localDeclaration)); await TestAsync<VariableDeclaratorSyntax>(GetTestText(localDeclarator)); static string GetTestText(string data) { return @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; } } #endregion #region Extractions [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration() { var testText = @" using System; class C { void M() { [|var a = {|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclaration2() { var testText = @" using System; class C { void M() { var a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromAssignment() { var testText = @" using System; class C { void M() { object a; a = [|{|result:new object()|};|] } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator() { var testText = @" using System; class C { void M() { var [|a = {|result:new object()|}|]; } }"; await TestAsync<ObjectCreationExpressionSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractFromDeclarator2() { var testText = @" using System; class C { void M() { {|result:var [|a = new object()|];|} } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestExtractInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:[Test] public i[||]nt a { get; set; }|} }"; await TestAsync<PropertyDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingExtractNotInHeaderOfProperty() { var testText = @" using System; class C { class TestAttribute : Attribute { } [Test] public int a { [||]get; set; } }"; await TestMissingAsync<PropertyDeclarationSyntax>(testText); } #endregion #region Headers & holes [Theory] [InlineData("var aa = nul[||]l;")] [InlineData("var aa = n[||]ull;")] [InlineData("string aa = null, bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingInHeaderHole(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("{|result:[||]var aa = null;|}")] [InlineData("{|result:var aa = [||]null;|}")] [InlineData("{|result:var aa = null[||];|}")] [InlineData("{|result:string aa = null, b[||]b = null;|}")] [InlineData("{|result:string aa = null, bb = [||]null;|}")] [InlineData("{|result:string aa = null, bb = null[||];|}")] [InlineData("{|result:string aa = null, bb = null;[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region TestHidden [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestNextToHidden2() { var testText = @" #line default class C { void M() { #line hidden var a = b; #line default {|result:C [||]LocalFunction(C c) { return null; }|} #line hidden var a = b; #line default } }"; await TestAsync<LocalFunctionStatementSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingHidden() { var testText = @" #line default class C { void M() { #line hidden C LocalFunction(C c) #line default { return null; }[||] } }"; await TestMissingAsync<LocalFunctionStatementSyntax>(testText); } #endregion #region Test predicate [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingPredicate() { var testText = @" class C { void M() { N([||]2+3); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgument() { var testText = @" class C { void M() { N({|result:[||]2+3|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestPredicate() { var testText = @" class C { void M() { var a = ({|result:[||]2 + 3|}, 2 + 3); } }"; await TestAsync<ArgumentSyntax>(testText, n => n.Parent is TupleExpressionSyntax); } #endregion #region Test arguments [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = [||]42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectInitializer() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = [|42|], int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectComma() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test]int a = 42[|,|] int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsInAttributes() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([[||]Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|int|] a = 42, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingArgumentsExtractionsSelectType2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([Test][|C|] a = null, int b = 41) {} }"; await TestMissingAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsAtTheEnd() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int a = 42[||]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsBefore() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([||]{|result:[Test]int a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParamName() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test]int [|a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam1() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a|] = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam2() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C([|{|result:[Test]int a = 42|}|], int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsSelectParam3() { var testText = @" using System; class C { class TestAttribute : Attribute { } public C({|result:[Test][|int a = 42|]|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestArgumentsExtractionsInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } public CC({|result:[Test]C[||]C a = 42|}, int b = 41) {} }"; await TestAsync<ParameterSyntax>(testText); } #endregion #region Test methods [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingMethodExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } public void [|I|].A([Test]int a = 42, int b = 41) {} }"; await TestMissingAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodCaretBeforeInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [||]I.A([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodNameAndExplicitInterfaceSelection() { var testText = @" using System; class C { class TestAttribute : Attribute { } {|result:public void [|I.A|]([Test]int a = 42, int b = 41) {}|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMethodInHeader() { var testText = @" using System; class CC { class TestAttribute : Attribute { } {|result:public C[||]C I.A([Test]int a = 42, int b = 41) { return null; }|} }"; await TestAsync<MethodDeclarationSyntax>(testText); } #endregion #region TestLocalDeclaration [Theory] [InlineData("{|result:v[||]ar name = \"\";|}")] [InlineData("{|result:string name = \"\", b[||]b = null;|}")] [InlineData("{|result:var[||] name = \"\";|}")] [InlineData("{|result:var [||]name = \"\";|}")] [InlineData("{|result:var na[||]me = \"\";|}")] [InlineData("{|result:var name[||] = \"\";|}")] [InlineData("{|result:var name [||]= \"\";|}")] [InlineData("{|result:var name =[||] \"\";|}")] [InlineData("{|result:var name = [||]\"\";|}")] [InlineData("{|result:[|var name = \"\";|]|}")] [InlineData("{|result:var name = \"\"[||];|}")] [InlineData("{|result:var name = \"\";[||]|}")] [InlineData("{|result:var name = \"\"[||]|}")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestLocalDeclarationInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestAsync<LocalDeclarationStatementSyntax>(testText); } [Theory] [InlineData("var name = \"[||]\";")] [InlineData("var name=[|\"\"|];")] [InlineData("string name = \"\", bb = n[||]ull;")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingLocalDeclarationCaretInHeader(string data) { var testText = @" class C { void M() { C LocalFunction(C c) { " + data + @"return null; } var a = new object(); } }"; await TestMissingAsync<LocalDeclarationStatementSyntax>(testText); } #endregion #region Test Ifs [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection1() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); }|] else if (b) { b(); } else { c(); }|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMultiline_IfElseIfElseSelection2() { await TestAsync<IfStatementSyntax>( @"class A { void Goo() { {|result:[|if (a) { a(); } else if (b) { b(); } else { c(); }|]|} } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact] public async Task TestMissingMultiline_IfElseIfElseSelection() { await TestMissingAsync<IfStatementSyntax>( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } #endregion #region Test Deep in expression [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepIn() { var testText = @" class C { void M() { N({|result:2+[||]3+4|}); } void N(int a) { } }"; await TestAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestMissingDeepInSecondRow() { var testText = @" class C { void M() { N(2 +[||]3+4); } void N(int a) { } }"; await TestMissingAsync<ArgumentSyntax>(testText); } [Fact] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task TestDeepInExpression() { var testText = @" class C { void M() { var b = ({|result:N(2[||])|}, 0); } int N(int a) { return a; } }"; await TestAsync<ArgumentSyntax>(testText, predicate: n => n.Parent is TupleExpressionSyntax); } #endregion } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Features/Core/Portable/InlineHints/InlineHintsOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.InlineHints { internal static class InlineHintsOptions { public static readonly Option2<bool> DisplayAllHintsWhilePressingAltF1 = new(nameof(InlineHintsOptions), nameof(DisplayAllHintsWhilePressingAltF1), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.Specific.DisplayAllHintsWhilePressingAltF1")); public static readonly PerLanguageOption2<bool> ColorHints = new(nameof(InlineHintsOptions), nameof(ColorHints), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ColorHints")); /// <summary> /// Non-persisted option used to switch to displaying everything while the user is holding ctrl-alt. /// </summary> public static readonly Option2<bool> DisplayAllOverride = new(nameof(DisplayAllOverride), nameof(EnabledForParameters), defaultValue: false); public static readonly PerLanguageOption2<bool> EnabledForParameters = new(nameof(InlineHintsOptions), nameof(EnabledForParameters), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints")); public static readonly PerLanguageOption2<bool> ForLiteralParameters = new(nameof(InlineHintsOptions), nameof(ForLiteralParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForLiteralParameters")); public static readonly PerLanguageOption2<bool> ForObjectCreationParameters = new(nameof(InlineHintsOptions), nameof(ForObjectCreationParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForObjectCreationParameters")); public static readonly PerLanguageOption2<bool> ForOtherParameters = new(nameof(InlineHintsOptions), nameof(ForOtherParameters), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForOtherParameters")); public static readonly PerLanguageOption2<bool> ForIndexerParameters = new(nameof(InlineHintsOptions), nameof(ForIndexerParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForArrayIndexers")); public static readonly PerLanguageOption2<bool> SuppressForParametersThatDifferOnlyBySuffix = new(nameof(InlineHintsOptions), nameof(SuppressForParametersThatDifferOnlyBySuffix), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.SuppressForParametersThatDifferOnlyBySuffix")); public static readonly PerLanguageOption2<bool> SuppressForParametersThatMatchMethodIntent = new(nameof(InlineHintsOptions), nameof(SuppressForParametersThatMatchMethodIntent), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.SuppressForParametersThatMatchMethodIntent")); public static readonly PerLanguageOption2<bool> EnabledForTypes = new(nameof(InlineHintsOptions), nameof(EnabledForTypes), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints")); public static readonly PerLanguageOption2<bool> ForImplicitVariableTypes = new(nameof(InlineHintsOptions), nameof(ForImplicitVariableTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitVariableTypes")); public static readonly PerLanguageOption2<bool> ForLambdaParameterTypes = new(nameof(InlineHintsOptions), nameof(ForLambdaParameterTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForLambdaParameterTypes")); public static readonly PerLanguageOption2<bool> ForImplicitObjectCreation = new(nameof(InlineHintsOptions), nameof(ForImplicitObjectCreation), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitObjectCreation")); } [ExportOptionProvider, Shared] internal sealed class InlineHintsOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( InlineHintsOptions.DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.ColorHints, InlineHintsOptions.EnabledForParameters, InlineHintsOptions.ForLiteralParameters, InlineHintsOptions.ForIndexerParameters, InlineHintsOptions.ForObjectCreationParameters, InlineHintsOptions.ForOtherParameters, InlineHintsOptions.EnabledForTypes, InlineHintsOptions.ForImplicitVariableTypes, InlineHintsOptions.ForLambdaParameterTypes, InlineHintsOptions.ForImplicitObjectCreation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.InlineHints { internal static class InlineHintsOptions { public static readonly Option2<bool> DisplayAllHintsWhilePressingAltF1 = new(nameof(InlineHintsOptions), nameof(DisplayAllHintsWhilePressingAltF1), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.Specific.DisplayAllHintsWhilePressingAltF1")); public static readonly PerLanguageOption2<bool> ColorHints = new(nameof(InlineHintsOptions), nameof(ColorHints), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ColorHints")); /// <summary> /// Non-persisted option used to switch to displaying everything while the user is holding ctrl-alt. /// </summary> public static readonly Option2<bool> DisplayAllOverride = new(nameof(DisplayAllOverride), nameof(EnabledForParameters), defaultValue: false); public static readonly PerLanguageOption2<bool> EnabledForParameters = new(nameof(InlineHintsOptions), nameof(EnabledForParameters), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints")); public static readonly PerLanguageOption2<bool> ForLiteralParameters = new(nameof(InlineHintsOptions), nameof(ForLiteralParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForLiteralParameters")); public static readonly PerLanguageOption2<bool> ForObjectCreationParameters = new(nameof(InlineHintsOptions), nameof(ForObjectCreationParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForObjectCreationParameters")); public static readonly PerLanguageOption2<bool> ForOtherParameters = new(nameof(InlineHintsOptions), nameof(ForOtherParameters), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForOtherParameters")); public static readonly PerLanguageOption2<bool> ForIndexerParameters = new(nameof(InlineHintsOptions), nameof(ForIndexerParameters), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.ForArrayIndexers")); public static readonly PerLanguageOption2<bool> SuppressForParametersThatDifferOnlyBySuffix = new(nameof(InlineHintsOptions), nameof(SuppressForParametersThatDifferOnlyBySuffix), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.SuppressForParametersThatDifferOnlyBySuffix")); public static readonly PerLanguageOption2<bool> SuppressForParametersThatMatchMethodIntent = new(nameof(InlineHintsOptions), nameof(SuppressForParametersThatMatchMethodIntent), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineParameterNameHints.SuppressForParametersThatMatchMethodIntent")); public static readonly PerLanguageOption2<bool> EnabledForTypes = new(nameof(InlineHintsOptions), nameof(EnabledForTypes), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints")); public static readonly PerLanguageOption2<bool> ForImplicitVariableTypes = new(nameof(InlineHintsOptions), nameof(ForImplicitVariableTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitVariableTypes")); public static readonly PerLanguageOption2<bool> ForLambdaParameterTypes = new(nameof(InlineHintsOptions), nameof(ForLambdaParameterTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForLambdaParameterTypes")); public static readonly PerLanguageOption2<bool> ForImplicitObjectCreation = new(nameof(InlineHintsOptions), nameof(ForImplicitObjectCreation), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitObjectCreation")); } [ExportOptionProvider, Shared] internal sealed class InlineHintsOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineHintsOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( InlineHintsOptions.DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.ColorHints, InlineHintsOptions.EnabledForParameters, InlineHintsOptions.ForLiteralParameters, InlineHintsOptions.ForIndexerParameters, InlineHintsOptions.ForObjectCreationParameters, InlineHintsOptions.ForOtherParameters, InlineHintsOptions.EnabledForTypes, InlineHintsOptions.ForImplicitVariableTypes, InlineHintsOptions.ForLambdaParameterTypes, InlineHintsOptions.ForImplicitObjectCreation); } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/Core/Portable/InternalUtilities/StackGuard.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis { internal static class StackGuard { public const int MaxUncheckedRecursionDepth = 20; /// <summary> /// Ensures that the remaining stack space is large enough to execute /// the average function. /// </summary> /// <param name="recursionDepth">how many times the calling function has recursed</param> /// <exception cref="InsufficientExecutionStackException"> /// The available stack space is insufficient to execute /// the average function. /// </exception> [DebuggerStepThrough] public static void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > MaxUncheckedRecursionDepth) { RuntimeHelpers.EnsureSufficientExecutionStack(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis { internal static class StackGuard { public const int MaxUncheckedRecursionDepth = 20; /// <summary> /// Ensures that the remaining stack space is large enough to execute /// the average function. /// </summary> /// <param name="recursionDepth">how many times the calling function has recursed</param> /// <exception cref="InsufficientExecutionStackException"> /// The available stack space is insufficient to execute /// the average function. /// </exception> [DebuggerStepThrough] public static void EnsureSufficientExecutionStack(int recursionDepth) { if (recursionDepth > MaxUncheckedRecursionDepth) { RuntimeHelpers.EnsureSufficientExecutionStack(); } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IfStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIfStatement(BoundIfStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitStatement(node.Consequence); Debug.Assert(rewrittenConsequence is { }); var rewrittenAlternative = VisitStatement(node.AlternativeOpt); var syntax = (IfStatementSyntax)node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (this.Instrument && !node.WasCompilerGenerated) { rewrittenCondition = _instrumenter.InstrumentIfStatementCondition(node, rewrittenCondition, _factory); } var result = RewriteIfStatement(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.HasErrors); // add sequence point before the whole statement if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentIfStatement(node, result); } return result; } private static BoundStatement RewriteIfStatement( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundStatement rewrittenConsequence, BoundStatement? rewrittenAlternativeOpt, bool hasErrors) { var afterif = new GeneratedLabelSymbol("afterif"); var builder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenAlternativeOpt == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, afterif)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); var statements = builder.ToImmutableAndFree(); return new BoundStatementList(syntax, statements, hasErrors); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: var alt = new GeneratedLabelSymbol("alternative"); builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, alt)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundGotoStatement(syntax, afterif)); builder.Add(new BoundLabelStatement(syntax, alt)); builder.Add(rewrittenAlternativeOpt); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); return new BoundStatementList(syntax, builder.ToImmutableAndFree(), hasErrors); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIfStatement(BoundIfStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitStatement(node.Consequence); Debug.Assert(rewrittenConsequence is { }); var rewrittenAlternative = VisitStatement(node.AlternativeOpt); var syntax = (IfStatementSyntax)node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (this.Instrument && !node.WasCompilerGenerated) { rewrittenCondition = _instrumenter.InstrumentIfStatementCondition(node, rewrittenCondition, _factory); } var result = RewriteIfStatement(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.HasErrors); // add sequence point before the whole statement if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentIfStatement(node, result); } return result; } private static BoundStatement RewriteIfStatement( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundStatement rewrittenConsequence, BoundStatement? rewrittenAlternativeOpt, bool hasErrors) { var afterif = new GeneratedLabelSymbol("afterif"); var builder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenAlternativeOpt == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, afterif)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); var statements = builder.ToImmutableAndFree(); return new BoundStatementList(syntax, statements, hasErrors); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: var alt = new GeneratedLabelSymbol("alternative"); builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, alt)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundGotoStatement(syntax, afterif)); builder.Add(new BoundLabelStatement(syntax, alt)); builder.Add(rewrittenAlternativeOpt); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); return new BoundStatementList(syntax, builder.ToImmutableAndFree(), hasErrors); } } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousDelegate_TemplateSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private Class AnonymousDelegateTemplateSymbol Inherits AnonymousTypeOrDelegateTemplateSymbol Private Const s_ctorIndex As Integer = 0 Private Const s_beginInvokeIndex As Integer = 1 Private Const s_endInvokeIndex As Integer = 2 Private Const s_invokeIndex As Integer = 3 Protected ReadOnly TypeDescr As AnonymousTypeDescriptor Private ReadOnly _members As ImmutableArray(Of SynthesizedDelegateMethodSymbol) Friend Shared Function Create(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) As AnonymousDelegateTemplateSymbol Dim parameters = typeDescr.Parameters Return If(parameters.Length = 1 AndAlso parameters.IsSubDescription(), New NonGenericAnonymousDelegateSymbol(manager, typeDescr), New AnonymousDelegateTemplateSymbol(manager, typeDescr)) End Function Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Debug.Assert(typeDescr.Parameters.Length > 1 OrElse Not typeDescr.Parameters.IsSubDescription() OrElse TypeOf Me Is NonGenericAnonymousDelegateSymbol) Me.TypeDescr = typeDescr Dim parameterDescriptors As ImmutableArray(Of AnonymousTypeField) = typeDescr.Parameters Dim returnType As TypeSymbol = If(parameterDescriptors.IsSubDescription(), DirectCast(manager.System_Void, TypeSymbol), Me.TypeParameters.Last) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(parameterDescriptors.Length + 1) Dim i As Integer ' A delegate has the following members: (see CLI spec 13.6) ' (1) a method named Invoke with the specified signature Dim delegateInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindDelegateInvoke, returnType) For i = 0 To parameterDescriptors.Length - 2 parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateInvoke, Me.TypeParameters(i), i, parameterDescriptors(i).IsByRef, parameterDescriptors(i).Name, i)) Next delegateInvoke.SetParameters(parameters.ToImmutable()) parameters.Clear() ' (2) a constructor with argument types (object, System.IntPtr) Dim delegateCtor = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.InstanceConstructorName, Me, SourceNamedTypeSymbol.DelegateConstructorMethodFlags, manager.System_Void) delegateCtor.SetParameters( ImmutableArray.Create(Of ParameterSymbol)( New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_Object, 0, False, StringConstants.DelegateConstructorInstanceParameterName), New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_IntPtr, 1, False, StringConstants.DelegateConstructorMethodParameterName) )) Dim delegateBeginInvoke As SynthesizedDelegateMethodSymbol Dim delegateEndInvoke As SynthesizedDelegateMethodSymbol ' Don't add Begin/EndInvoke members to winmd compilations. ' Invoke must be the last member, regardless. If Me.IsCompilationOutputWinMdObj() Then delegateBeginInvoke = Nothing delegateEndInvoke = Nothing _members = ImmutableArray.Create(delegateCtor, delegateInvoke) Else ' (3) BeginInvoke delegateBeginInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateBeginInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindOrdinary, manager.System_IAsyncResult) For i = 0 To delegateInvoke.ParameterCount - 1 Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, parameter.Type, i, parameter.IsByRef(), parameter.Name, i)) Next parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_AsyncCallback, i, False, StringConstants.DelegateMethodCallbackParameterName)) i += 1 parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_Object, i, False, StringConstants.DelegateMethodInstanceParameterName)) delegateBeginInvoke.SetParameters(parameters.ToImmutable()) parameters.Clear() ' and (4) EndInvoke methods delegateEndInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateEndInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindOrdinary, returnType) Dim ordinal As Integer = 0 For i = 0 To delegateInvoke.ParameterCount - 1 Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) If parameter.IsByRef Then parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, parameter.Type, ordinal, parameter.IsByRef(), parameter.Name, i)) ordinal += 1 End If Next parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, manager.System_IAsyncResult, ordinal, False, StringConstants.DelegateMethodResultParameterName)) delegateEndInvoke.SetParameters(parameters.ToImmutable()) _members = ImmutableArray.Create(delegateCtor, delegateBeginInvoke, delegateEndInvoke, delegateInvoke) End If Debug.Assert(_members.All(Function(m) m IsNot Nothing)) parameters.Free() End Sub Friend Overrides Function GetAnonymousTypeKey() As AnonymousTypeKey Dim parameters = TypeDescr.Parameters.SelectAsArray(Function(p) New AnonymousTypeKeyField(p.Name, isKey:=p.IsByRef, ignoreCase:=True)) Return New AnonymousTypeKey(parameters, isDelegate:=True) End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return StaticCast(Of Symbol).From(_members) End Function Friend NotOverridable Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)() End Function Friend Overrides ReadOnly Property GeneratedNamePrefix As String Get Return GeneratedNameConstants.AnonymousDelegateTemplateNamePrefix End Get End Property Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return Manager.System_MulticastDelegate End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property DelegateInvokeMethod As MethodSymbol Get ' The invoke method is always the last method, in regular or winmd scenarios Return _members(_members.Length - 1) End Get End Property Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Delegate End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Attribute: System.Runtime.CompilerServices.CompilerGeneratedAttribute() AddSynthesizedAttribute(attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' Attribute: System.Diagnostics.DebuggerDisplayAttribute("<generated method>",Type := "<generated method>") Dim value As New TypedConstant(Manager.System_String, TypedConstantKind.Primitive, "<generated method>") AddSynthesizedAttribute(attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor, ImmutableArray.Create(value), ImmutableArray.Create(New KeyValuePair(Of WellKnownMember, TypedConstant)( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__Type, value)))) End Sub End Class ''' <summary> ''' This is a symbol to represent Anonymous Delegate for a lambda ''' like: ''' Sub() ... ''' ''' This delegate type doesn't have generic parameters. Unlike generic anonymous types, ''' for which we are constructing new instance of substituted symbol for each use site ''' with reference to the location, we are creating new instance of this symbol with its ''' own location for each use site. But all of them are representing the same delegate ''' type and are going to be equal to each other. ''' </summary> Private NotInheritable Class NonGenericAnonymousDelegateSymbol Inherits AnonymousDelegateTemplateSymbol Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Debug.Assert(typeDescr.Parameters.Length = 1) Debug.Assert(typeDescr.Parameters.IsSubDescription()) End Sub Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(TypeDescr.Location) End Get End Property Public Overrides Function GetHashCode() As Integer Return Manager.GetHashCode() End Function Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean If obj Is Me Then Return True End If Dim other = TryCast(obj, NonGenericAnonymousDelegateSymbol) Return other IsNot Nothing AndAlso other.Manager Is Me.Manager 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.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private Class AnonymousDelegateTemplateSymbol Inherits AnonymousTypeOrDelegateTemplateSymbol Private Const s_ctorIndex As Integer = 0 Private Const s_beginInvokeIndex As Integer = 1 Private Const s_endInvokeIndex As Integer = 2 Private Const s_invokeIndex As Integer = 3 Protected ReadOnly TypeDescr As AnonymousTypeDescriptor Private ReadOnly _members As ImmutableArray(Of SynthesizedDelegateMethodSymbol) Friend Shared Function Create(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) As AnonymousDelegateTemplateSymbol Dim parameters = typeDescr.Parameters Return If(parameters.Length = 1 AndAlso parameters.IsSubDescription(), New NonGenericAnonymousDelegateSymbol(manager, typeDescr), New AnonymousDelegateTemplateSymbol(manager, typeDescr)) End Function Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Debug.Assert(typeDescr.Parameters.Length > 1 OrElse Not typeDescr.Parameters.IsSubDescription() OrElse TypeOf Me Is NonGenericAnonymousDelegateSymbol) Me.TypeDescr = typeDescr Dim parameterDescriptors As ImmutableArray(Of AnonymousTypeField) = typeDescr.Parameters Dim returnType As TypeSymbol = If(parameterDescriptors.IsSubDescription(), DirectCast(manager.System_Void, TypeSymbol), Me.TypeParameters.Last) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance(parameterDescriptors.Length + 1) Dim i As Integer ' A delegate has the following members: (see CLI spec 13.6) ' (1) a method named Invoke with the specified signature Dim delegateInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindDelegateInvoke, returnType) For i = 0 To parameterDescriptors.Length - 2 parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateInvoke, Me.TypeParameters(i), i, parameterDescriptors(i).IsByRef, parameterDescriptors(i).Name, i)) Next delegateInvoke.SetParameters(parameters.ToImmutable()) parameters.Clear() ' (2) a constructor with argument types (object, System.IntPtr) Dim delegateCtor = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.InstanceConstructorName, Me, SourceNamedTypeSymbol.DelegateConstructorMethodFlags, manager.System_Void) delegateCtor.SetParameters( ImmutableArray.Create(Of ParameterSymbol)( New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_Object, 0, False, StringConstants.DelegateConstructorInstanceParameterName), New AnonymousTypeOrDelegateParameterSymbol(delegateCtor, manager.System_IntPtr, 1, False, StringConstants.DelegateConstructorMethodParameterName) )) Dim delegateBeginInvoke As SynthesizedDelegateMethodSymbol Dim delegateEndInvoke As SynthesizedDelegateMethodSymbol ' Don't add Begin/EndInvoke members to winmd compilations. ' Invoke must be the last member, regardless. If Me.IsCompilationOutputWinMdObj() Then delegateBeginInvoke = Nothing delegateEndInvoke = Nothing _members = ImmutableArray.Create(delegateCtor, delegateInvoke) Else ' (3) BeginInvoke delegateBeginInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateBeginInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindOrdinary, manager.System_IAsyncResult) For i = 0 To delegateInvoke.ParameterCount - 1 Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, parameter.Type, i, parameter.IsByRef(), parameter.Name, i)) Next parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_AsyncCallback, i, False, StringConstants.DelegateMethodCallbackParameterName)) i += 1 parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateBeginInvoke, manager.System_Object, i, False, StringConstants.DelegateMethodInstanceParameterName)) delegateBeginInvoke.SetParameters(parameters.ToImmutable()) parameters.Clear() ' and (4) EndInvoke methods delegateEndInvoke = New SynthesizedDelegateMethodSymbol(WellKnownMemberNames.DelegateEndInvokeName, Me, SourceNamedTypeSymbol.DelegateCommonMethodFlags Or SourceMemberFlags.MethodKindOrdinary, returnType) Dim ordinal As Integer = 0 For i = 0 To delegateInvoke.ParameterCount - 1 Dim parameter As ParameterSymbol = delegateInvoke.Parameters(i) If parameter.IsByRef Then parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, parameter.Type, ordinal, parameter.IsByRef(), parameter.Name, i)) ordinal += 1 End If Next parameters.Add(New AnonymousTypeOrDelegateParameterSymbol(delegateEndInvoke, manager.System_IAsyncResult, ordinal, False, StringConstants.DelegateMethodResultParameterName)) delegateEndInvoke.SetParameters(parameters.ToImmutable()) _members = ImmutableArray.Create(delegateCtor, delegateBeginInvoke, delegateEndInvoke, delegateInvoke) End If Debug.Assert(_members.All(Function(m) m IsNot Nothing)) parameters.Free() End Sub Friend Overrides Function GetAnonymousTypeKey() As AnonymousTypeKey Dim parameters = TypeDescr.Parameters.SelectAsArray(Function(p) New AnonymousTypeKeyField(p.Name, isKey:=p.IsByRef, ignoreCase:=True)) Return New AnonymousTypeKey(parameters, isDelegate:=True) End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return StaticCast(Of Symbol).From(_members) End Function Friend NotOverridable Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)() End Function Friend Overrides ReadOnly Property GeneratedNamePrefix As String Get Return GeneratedNameConstants.AnonymousDelegateTemplateNamePrefix End Get End Property Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return Manager.System_MulticastDelegate End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property DelegateInvokeMethod As MethodSymbol Get ' The invoke method is always the last method, in regular or winmd scenarios Return _members(_members.Length - 1) End Get End Property Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Delegate End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Attribute: System.Runtime.CompilerServices.CompilerGeneratedAttribute() AddSynthesizedAttribute(attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' Attribute: System.Diagnostics.DebuggerDisplayAttribute("<generated method>",Type := "<generated method>") Dim value As New TypedConstant(Manager.System_String, TypedConstantKind.Primitive, "<generated method>") AddSynthesizedAttribute(attributes, Manager.Compilation.TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor, ImmutableArray.Create(value), ImmutableArray.Create(New KeyValuePair(Of WellKnownMember, TypedConstant)( WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__Type, value)))) End Sub End Class ''' <summary> ''' This is a symbol to represent Anonymous Delegate for a lambda ''' like: ''' Sub() ... ''' ''' This delegate type doesn't have generic parameters. Unlike generic anonymous types, ''' for which we are constructing new instance of substituted symbol for each use site ''' with reference to the location, we are creating new instance of this symbol with its ''' own location for each use site. But all of them are representing the same delegate ''' type and are going to be equal to each other. ''' </summary> Private NotInheritable Class NonGenericAnonymousDelegateSymbol Inherits AnonymousDelegateTemplateSymbol Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Debug.Assert(typeDescr.Parameters.Length = 1) Debug.Assert(typeDescr.Parameters.IsSubDescription()) End Sub Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(TypeDescr.Location) End Get End Property Public Overrides Function GetHashCode() As Integer Return Manager.GetHashCode() End Function Public Overrides Function Equals(obj As TypeSymbol, comparison As TypeCompareKind) As Boolean If obj Is Me Then Return True End If Dim other = TryCast(obj, NonGenericAnonymousDelegateSymbol) Return other IsNot Nothing AndAlso other.Manager Is Me.Manager End Function End Class End Class End Namespace
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./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
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/ImportAliasClauseSyntaxClassifier.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.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class ImportAliasClauseSyntaxClassifier Inherits AbstractSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(GetType(ImportAliasClauseSyntax)) Public Overrides Sub AddClassifications(workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) ClassifyImportAliasClauseSyntax(DirectCast(syntax, ImportAliasClauseSyntax), semanticModel, result, cancellationToken) End Sub Private Shared Sub ClassifyImportAliasClauseSyntax( node As ImportAliasClauseSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim symbolInfo = semanticModel.GetTypeInfo(DirectCast(node.Parent, SimpleImportsClauseSyntax).Name, cancellationToken) If symbolInfo.Type IsNot Nothing Then Dim classification = GetClassificationForType(symbolInfo.Type) If classification IsNot Nothing Then Dim token = node.Identifier result.Add(New ClassifiedSpan(token.Span, classification)) Return End If End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Friend Class ImportAliasClauseSyntaxClassifier Inherits AbstractSyntaxClassifier Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(GetType(ImportAliasClauseSyntax)) Public Overrides Sub AddClassifications(workspace As Workspace, syntax As SyntaxNode, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) ClassifyImportAliasClauseSyntax(DirectCast(syntax, ImportAliasClauseSyntax), semanticModel, result, cancellationToken) End Sub Private Shared Sub ClassifyImportAliasClauseSyntax( node As ImportAliasClauseSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim symbolInfo = semanticModel.GetTypeInfo(DirectCast(node.Parent, SimpleImportsClauseSyntax).Name, cancellationToken) If symbolInfo.Type IsNot Nothing Then Dim classification = GetClassificationForType(symbolInfo.Type) If classification IsNot Nothing Then Dim token = node.Identifier result.Add(New ClassifiedSpan(token.Span, classification)) Return End If End If End Sub End Class End Namespace
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/Core/Portable/CodeGen/PermissionSetAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// This class represents the PermissionSetAttribute specified in source which needs 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 at ndp\clr\src\vm\securityattributes.cpp. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path: This is done during binding. /// 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 (see method <see cref="ConvertToHex"/>). /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// </remarks> internal class PermissionSetAttributeWithFileReference : Cci.ICustomAttribute { private readonly Cci.ICustomAttribute _sourceAttribute; private readonly string _resolvedPermissionSetFilePath; internal const string FilePropertyName = "File"; internal const string HexPropertyName = "Hex"; public PermissionSetAttributeWithFileReference(Cci.ICustomAttribute sourceAttribute, string resolvedPermissionSetFilePath) { RoslynDebug.Assert(resolvedPermissionSetFilePath != null); _sourceAttribute = sourceAttribute; _resolvedPermissionSetFilePath = resolvedPermissionSetFilePath; } /// <summary> /// Zero or more positional arguments for the attribute constructor. /// </summary> public ImmutableArray<Cci.IMetadataExpression> GetArguments(EmitContext context) { return _sourceAttribute.GetArguments(context); } /// <summary> /// A reference to the constructor that will be used to instantiate this custom attribute during execution (if the attribute is inspected via Reflection). /// </summary> public Cci.IMethodReference Constructor(EmitContext context, bool reportDiagnostics) => _sourceAttribute.Constructor(context, reportDiagnostics); /// <summary> /// Zero or more named arguments that specify values for fields and properties of the attribute. /// </summary> public ImmutableArray<Cci.IMetadataNamedArgument> GetNamedArguments(EmitContext context) { // Perform fixup Cci.ITypeReference stringType = context.Module.GetPlatformType(Cci.PlatformType.SystemString, context); #if DEBUG // Must have exactly 1 named argument. var namedArgs = _sourceAttribute.GetNamedArguments(context); Debug.Assert(namedArgs.Length == 1); // Named argument must be 'File' property of string type var fileArg = namedArgs.First(); Debug.Assert(fileArg.ArgumentName == FilePropertyName); Debug.Assert(context.Module.IsPlatformType(fileArg.Type, Cci.PlatformType.SystemString)); // Named argument value must be a non-empty string Debug.Assert(fileArg.ArgumentValue is MetadataConstant); var fileName = (string?)((MetadataConstant)fileArg.ArgumentValue).Value; Debug.Assert(!String.IsNullOrEmpty(fileName)); // PermissionSetAttribute type must have a writable public string type property member 'Hex' ISymbol iSymbol = _sourceAttribute.GetType(context).GetInternalSymbol()!.GetISymbol(); Debug.Assert(((INamedTypeSymbol)iSymbol).GetMembers(HexPropertyName).Any( member => member.Kind == SymbolKind.Property && ((IPropertySymbol)member).Type.SpecialType == SpecialType.System_String)); #endif string hexFileContent; // Read the file contents at the resolved file path into a byte array. // May throw PermissionSetFileReadException, which is handled in Compilation.Emit. var resolver = context.Module.CommonCompilation.Options.XmlReferenceResolver; // If the resolver isn't available we won't get here since we had to use it to resolve the path. RoslynDebug.Assert(resolver != null); try { using (Stream stream = resolver.OpenReadChecked(_resolvedPermissionSetFilePath)) { // Convert the byte array contents into a string in hexadecimal format. hexFileContent = ConvertToHex(stream); } } catch (IOException e) { throw new PermissionSetFileReadException(e.Message, _resolvedPermissionSetFilePath); } // Synthesize a named attribute argument "Hex = hexFileContent". return ImmutableArray.Create<Cci.IMetadataNamedArgument>(new HexPropertyMetadataNamedArgument(stringType, new MetadataConstant(stringType, hexFileContent))); } // internal for testing purposes. internal static string ConvertToHex(Stream stream) { RoslynDebug.Assert(stream != null); var pooledStrBuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrBuilder.Builder; int b; while ((b = stream.ReadByte()) >= 0) { stringBuilder.Append(ConvertHexToChar((b >> 4) & 0xf)); stringBuilder.Append(ConvertHexToChar(b & 0xf)); } return pooledStrBuilder.ToStringAndFree(); } private static char ConvertHexToChar(int b) { Debug.Assert(b < 0x10); return (char)(b < 10 ? '0' + b : 'a' + b - 10); } /// <summary> /// The number of positional arguments. /// </summary> public int ArgumentCount => _sourceAttribute.ArgumentCount; /// <summary> /// The number of named arguments. /// </summary> public ushort NamedArgumentCount { get { Debug.Assert(_sourceAttribute.NamedArgumentCount == 1); return 1; } } /// <summary> /// The type of the attribute. For example System.AttributeUsageAttribute. /// </summary> public Cci.ITypeReference GetType(EmitContext context) => _sourceAttribute.GetType(context); public bool AllowMultiple => _sourceAttribute.AllowMultiple; private struct HexPropertyMetadataNamedArgument : Cci.IMetadataNamedArgument { private readonly Cci.ITypeReference _type; private readonly Cci.IMetadataExpression _value; public HexPropertyMetadataNamedArgument(Cci.ITypeReference type, Cci.IMetadataExpression value) { _type = type; _value = value; } public string ArgumentName { get { return HexPropertyName; } } public Cci.IMetadataExpression ArgumentValue { get { return _value; } } public bool IsField { get { return false; } } Cci.ITypeReference Cci.IMetadataExpression.Type { get { return _type; } } void Cci.IMetadataExpression.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit(this); } } } /// <summary> /// Exception class to enable generating ERR_PermissionSetAttributeFileReadError while reading the file for PermissionSetAttribute fixup. /// </summary> internal class PermissionSetFileReadException : Exception { private readonly string _file; public PermissionSetFileReadException(string message, string file) : base(message) { _file = file; } public string FileName => _file; public string PropertyName => PermissionSetAttributeWithFileReference.FilePropertyName; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// This class represents the PermissionSetAttribute specified in source which needs 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 at ndp\clr\src\vm\securityattributes.cpp. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path: This is done during binding. /// 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 (see method <see cref="ConvertToHex"/>). /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// </remarks> internal class PermissionSetAttributeWithFileReference : Cci.ICustomAttribute { private readonly Cci.ICustomAttribute _sourceAttribute; private readonly string _resolvedPermissionSetFilePath; internal const string FilePropertyName = "File"; internal const string HexPropertyName = "Hex"; public PermissionSetAttributeWithFileReference(Cci.ICustomAttribute sourceAttribute, string resolvedPermissionSetFilePath) { RoslynDebug.Assert(resolvedPermissionSetFilePath != null); _sourceAttribute = sourceAttribute; _resolvedPermissionSetFilePath = resolvedPermissionSetFilePath; } /// <summary> /// Zero or more positional arguments for the attribute constructor. /// </summary> public ImmutableArray<Cci.IMetadataExpression> GetArguments(EmitContext context) { return _sourceAttribute.GetArguments(context); } /// <summary> /// A reference to the constructor that will be used to instantiate this custom attribute during execution (if the attribute is inspected via Reflection). /// </summary> public Cci.IMethodReference Constructor(EmitContext context, bool reportDiagnostics) => _sourceAttribute.Constructor(context, reportDiagnostics); /// <summary> /// Zero or more named arguments that specify values for fields and properties of the attribute. /// </summary> public ImmutableArray<Cci.IMetadataNamedArgument> GetNamedArguments(EmitContext context) { // Perform fixup Cci.ITypeReference stringType = context.Module.GetPlatformType(Cci.PlatformType.SystemString, context); #if DEBUG // Must have exactly 1 named argument. var namedArgs = _sourceAttribute.GetNamedArguments(context); Debug.Assert(namedArgs.Length == 1); // Named argument must be 'File' property of string type var fileArg = namedArgs.First(); Debug.Assert(fileArg.ArgumentName == FilePropertyName); Debug.Assert(context.Module.IsPlatformType(fileArg.Type, Cci.PlatformType.SystemString)); // Named argument value must be a non-empty string Debug.Assert(fileArg.ArgumentValue is MetadataConstant); var fileName = (string?)((MetadataConstant)fileArg.ArgumentValue).Value; Debug.Assert(!String.IsNullOrEmpty(fileName)); // PermissionSetAttribute type must have a writable public string type property member 'Hex' ISymbol iSymbol = _sourceAttribute.GetType(context).GetInternalSymbol()!.GetISymbol(); Debug.Assert(((INamedTypeSymbol)iSymbol).GetMembers(HexPropertyName).Any( member => member.Kind == SymbolKind.Property && ((IPropertySymbol)member).Type.SpecialType == SpecialType.System_String)); #endif string hexFileContent; // Read the file contents at the resolved file path into a byte array. // May throw PermissionSetFileReadException, which is handled in Compilation.Emit. var resolver = context.Module.CommonCompilation.Options.XmlReferenceResolver; // If the resolver isn't available we won't get here since we had to use it to resolve the path. RoslynDebug.Assert(resolver != null); try { using (Stream stream = resolver.OpenReadChecked(_resolvedPermissionSetFilePath)) { // Convert the byte array contents into a string in hexadecimal format. hexFileContent = ConvertToHex(stream); } } catch (IOException e) { throw new PermissionSetFileReadException(e.Message, _resolvedPermissionSetFilePath); } // Synthesize a named attribute argument "Hex = hexFileContent". return ImmutableArray.Create<Cci.IMetadataNamedArgument>(new HexPropertyMetadataNamedArgument(stringType, new MetadataConstant(stringType, hexFileContent))); } // internal for testing purposes. internal static string ConvertToHex(Stream stream) { RoslynDebug.Assert(stream != null); var pooledStrBuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrBuilder.Builder; int b; while ((b = stream.ReadByte()) >= 0) { stringBuilder.Append(ConvertHexToChar((b >> 4) & 0xf)); stringBuilder.Append(ConvertHexToChar(b & 0xf)); } return pooledStrBuilder.ToStringAndFree(); } private static char ConvertHexToChar(int b) { Debug.Assert(b < 0x10); return (char)(b < 10 ? '0' + b : 'a' + b - 10); } /// <summary> /// The number of positional arguments. /// </summary> public int ArgumentCount => _sourceAttribute.ArgumentCount; /// <summary> /// The number of named arguments. /// </summary> public ushort NamedArgumentCount { get { Debug.Assert(_sourceAttribute.NamedArgumentCount == 1); return 1; } } /// <summary> /// The type of the attribute. For example System.AttributeUsageAttribute. /// </summary> public Cci.ITypeReference GetType(EmitContext context) => _sourceAttribute.GetType(context); public bool AllowMultiple => _sourceAttribute.AllowMultiple; private struct HexPropertyMetadataNamedArgument : Cci.IMetadataNamedArgument { private readonly Cci.ITypeReference _type; private readonly Cci.IMetadataExpression _value; public HexPropertyMetadataNamedArgument(Cci.ITypeReference type, Cci.IMetadataExpression value) { _type = type; _value = value; } public string ArgumentName { get { return HexPropertyName; } } public Cci.IMetadataExpression ArgumentValue { get { return _value; } } public bool IsField { get { return false; } } Cci.ITypeReference Cci.IMetadataExpression.Type { get { return _type; } } void Cci.IMetadataExpression.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit(this); } } } /// <summary> /// Exception class to enable generating ERR_PermissionSetAttributeFileReadError while reading the file for PermissionSetAttribute fixup. /// </summary> internal class PermissionSetFileReadException : Exception { private readonly string _file; public PermissionSetFileReadException(string message, string file) : base(message) { _file = file; } public string FileName => _file; public string PropertyName => PermissionSetAttributeWithFileReference.FilePropertyName; } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Test/Perf/Utilities/RelativeDirectory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.IO.Compression; using System.Net; using System.Runtime.CompilerServices; namespace Roslyn.Test.Performance.Utilities { public class RelativeDirectory { private string _workingDir; public RelativeDirectory() { } public RelativeDirectory(string workingDir) { _workingDir = workingDir; } public void SetWorkingDirectory(string workingDir) { _workingDir = workingDir; } private void ThrowIfNotSetup() { if (_workingDir == null) { throw new InvalidOperationException("The test has not been set up correctly. Avoid doing any directory operations in the constructor."); } } /// <summary> /// Returns the current working directory that the test has access to. /// This is typically the same directory as the script is located in. /// </summary> public string MyWorkingDirectory { get { ThrowIfNotSetup(); return _workingDir; } } /// <summary> /// Returns a directory that the test can use for temporary file storage. /// </summary> public string TempDirectory { get { ThrowIfNotSetup(); var tempDirectory = Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\PerfTemp"); Directory.CreateDirectory(tempDirectory); return tempDirectory; } } /// <summary> /// Returns the directory that contains built roslyn binaries. Usually this will be /// Binaries/Debug or Binaries/Release. /// </summary> /// <returns></returns> public string MyBinaries() { ThrowIfNotSetup(); // The exceptation is that scripts calling this are included // in a project in the solution and have already been deployed // to a binaries folder foreach (var configuration in new string[] { "debug", "release" }) { var configurationIndex = _workingDir.IndexOf(configuration, StringComparison.CurrentCultureIgnoreCase); if (configurationIndex != -1) { return _workingDir.Substring(0, configurationIndex + configuration.Length); } } throw new Exception("Couldn't find binaries. Are you running from the binaries directory?"); } /// <returns> /// The path to TAO /// </returns> public string TaoPath => Path.Combine(MyBinaries(), "exes", "EditorTestApp", "Tao"); /// Downloads a zip from azure store and extracts it into /// the ./temp directory. /// /// If this current version has already been downloaded /// and extracted, do nothing. public void DownloadProject(string name, int version, ILogger logger) { ThrowIfNotSetup(); var zipFileName = $"{name}.{version}.zip"; var zipPath = Path.Combine(TempDirectory, zipFileName); // If we've already downloaded the zip, assume that it // has been downloaded *and* extracted. if (File.Exists(zipPath)) { logger.Log($"Didn't download and extract {zipFileName} because one already exists at {zipPath}."); return; } // Remove all .zip files that were downloaded before. foreach (var path in Directory.EnumerateFiles(TempDirectory, $"{name}.*.zip")) { logger.Log($"Removing old zip {path}"); File.Delete(path); } // Download zip file to temp directory var downloadTarget = $"https://dotnetci.blob.core.windows.net/roslyn-perf/{zipFileName}"; logger.Log($"Downloading {downloadTarget}"); var client = new WebClient(); client.DownloadFile(downloadTarget, zipPath); logger.Log($"Done Downloading"); // Extract to temp directory logger.Log($"Extracting {zipPath} to {TempDirectory}"); ZipFile.ExtractToDirectory(zipPath, TempDirectory); logger.Log($"Done Extracting"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.IO.Compression; using System.Net; using System.Runtime.CompilerServices; namespace Roslyn.Test.Performance.Utilities { public class RelativeDirectory { private string _workingDir; public RelativeDirectory() { } public RelativeDirectory(string workingDir) { _workingDir = workingDir; } public void SetWorkingDirectory(string workingDir) { _workingDir = workingDir; } private void ThrowIfNotSetup() { if (_workingDir == null) { throw new InvalidOperationException("The test has not been set up correctly. Avoid doing any directory operations in the constructor."); } } /// <summary> /// Returns the current working directory that the test has access to. /// This is typically the same directory as the script is located in. /// </summary> public string MyWorkingDirectory { get { ThrowIfNotSetup(); return _workingDir; } } /// <summary> /// Returns a directory that the test can use for temporary file storage. /// </summary> public string TempDirectory { get { ThrowIfNotSetup(); var tempDirectory = Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\PerfTemp"); Directory.CreateDirectory(tempDirectory); return tempDirectory; } } /// <summary> /// Returns the directory that contains built roslyn binaries. Usually this will be /// Binaries/Debug or Binaries/Release. /// </summary> /// <returns></returns> public string MyBinaries() { ThrowIfNotSetup(); // The exceptation is that scripts calling this are included // in a project in the solution and have already been deployed // to a binaries folder foreach (var configuration in new string[] { "debug", "release" }) { var configurationIndex = _workingDir.IndexOf(configuration, StringComparison.CurrentCultureIgnoreCase); if (configurationIndex != -1) { return _workingDir.Substring(0, configurationIndex + configuration.Length); } } throw new Exception("Couldn't find binaries. Are you running from the binaries directory?"); } /// <returns> /// The path to TAO /// </returns> public string TaoPath => Path.Combine(MyBinaries(), "exes", "EditorTestApp", "Tao"); /// Downloads a zip from azure store and extracts it into /// the ./temp directory. /// /// If this current version has already been downloaded /// and extracted, do nothing. public void DownloadProject(string name, int version, ILogger logger) { ThrowIfNotSetup(); var zipFileName = $"{name}.{version}.zip"; var zipPath = Path.Combine(TempDirectory, zipFileName); // If we've already downloaded the zip, assume that it // has been downloaded *and* extracted. if (File.Exists(zipPath)) { logger.Log($"Didn't download and extract {zipFileName} because one already exists at {zipPath}."); return; } // Remove all .zip files that were downloaded before. foreach (var path in Directory.EnumerateFiles(TempDirectory, $"{name}.*.zip")) { logger.Log($"Removing old zip {path}"); File.Delete(path); } // Download zip file to temp directory var downloadTarget = $"https://dotnetci.blob.core.windows.net/roslyn-perf/{zipFileName}"; logger.Log($"Downloading {downloadTarget}"); var client = new WebClient(); client.DownloadFile(downloadTarget, zipPath); logger.Log($"Done Downloading"); // Extract to temp directory logger.Log($"Extracting {zipPath} to {TempDirectory}"); ZipFile.ExtractToDirectory(zipPath, TempDirectory); logger.Log($"Done Extracting"); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/VisualStudio/Core/Def/ExternalAccess/VSTypeScript/Api/IVsTypeScriptTodoCommentService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.TodoComments; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { internal interface IVsTypeScriptTodoCommentService { /// <summary> /// Legacy entry-point to allow existing in-process TypeScript language service to report todo comments. /// TypeScript is responsible for determining when to compute todo comments (for example, on <see /// cref="Workspace.WorkspaceChanged"/>). This can be called on any thread. /// </summary> Task ReportTodoCommentsAsync(Document document, ImmutableArray<TodoComment> todoComments, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.TodoComments; namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api { internal interface IVsTypeScriptTodoCommentService { /// <summary> /// Legacy entry-point to allow existing in-process TypeScript language service to report todo comments. /// TypeScript is responsible for determining when to compute todo comments (for example, on <see /// cref="Workspace.WorkspaceChanged"/>). This can be called on any thread. /// </summary> Task ReportTodoCommentsAsync(Document document, ImmutableArray<TodoComment> todoComments, CancellationToken cancellationToken); } }
-1